javascript change position of element without string concatenation - javascript

Most of the answers to this question give solution similar to:
let x_pos=42, y_pos=43;
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
but isn't it expensive, just to change the postion, to convert the integers to string and do some concatenations?
I think the browser will probably do exactly the reverse calculations to get the integer values again.

It's not that expensive to concatenate strings in modern browsers nowadays. Here's a factory to move an element to a(nother) position, using a small helper for converting numbers to units.
// factory to avoid recreating [number2Unit] for every call and
// and delegate the actual styling to small methods.
function moveElToFactory(ux = `px`, uy = `px`) {
const number2Unit = (nr, unit) => `${nr}${unit}`;
const moveX = (el, x, unit) => el.style.left = number2Unit(x, unit);
const moveY = (el, y, unit) => el.style.top = number2Unit(y, unit);
return (el, x, y, uX = ux, uY = uy) => {
el.style.position = `absolute`;
y && moveY(el, y, uY);
x && moveX(el, x, uX);
}
}
// demo
const moveElTo = moveElToFactory();
setTimeout(() => {
const [d1, d2, d3] = [
document.querySelector('#div1'),
document.querySelector('#div2'),
document.querySelector('#div3')]
moveElTo(d1, 42, 43);
d1.textContent += ` [x, y] ${d1.style.left}, ${d1.style.top}`;
moveElTo(d2, 15, 50, `vw`, `%`);
d2.textContent += ` [x, y] ${d2.style.left}, ${d2.style.top}`;
moveElTo(d3, ...[,35,,`%`]);
d3.textContent += ` [x, y] 0, ${d3.style.top}`; }, 1000);
<div id="div1">where am I (div#div1)?</div>
<div id="div2">And where am I (div#div2)?</div>
<div id="div3">And I (div#div3) am where?</div>

Related

Calculate volume of FOV and loop inside

I want to improve performances in my game and for that, I need to loop inside the visible volume.
I know that this is very slow to calculate, but I really think that it'll be better that today.
I have these values:
Camera position: x, y, z
Camera rotation: rx, ry, rz
Render distance: d
Render function: r
I've tried this code but r is never executed:
const MAP_LIMIT = [150,25,150]; // Limit of the map (x,y,z)
(x=0,y=0,z=0,d=10,ox=0,oy=0,oz=0,r) => {
x = Int(x); // Int = Math.round
y = Int(y);
z = Int(z);
const RoundToMapLimit = (n=0,t=0) => n <= 0 ? 0 : (n >= MAP_LIMIT[t] ? MAP_LIMIT[t] : n);
const obj = new THREE.Object3D();
obj.position.set(x,y,z);
obj.rotation.set(ox,0,0);
obj.translateX(d);
const xRange = [RoundToMapLimit(x),RoundToMapLimit(obj.position.x)];
obj.translateX(-d);
obj.rotation.set(0,oy,0);
obj.translateY(d);
const yRange = [RoundToMapLimit(y,1),RoundToMapLimit(obj.position.y,1)];
obj.translateY(-d);
obj.rotation.set(0,0,oz);
obj.translateZ(d);
const zRange = [RoundToMapLimit(z,2),RoundToMapLimit(obj.position.z,2)];
for (let y2 = Math.min(...yRange); y2 < Math.max(...yRange); ++y2) {
for (let x2 = Math.min(...xRange); x2 < Math.max(...xRange); ++x2) {
for (let z2 = Math.min(...zRange); z2 < Math.max(...zRange); ++z2) {
r([x2,y2,z2]);
}
}
}
};
Can you please help me to fix this function ?
Thank you

Is HTML Canvas quadraticCurveTo() not exact?

Edit: I just changed my Control Point to the Intersection. That's why it couldn't fit anymore.
I know it's a very presumptuous. But I am working on a Web-Application and I need to calculate the intersection with a quadratic Beziere-Curve and a Line.
Linear Bezier-Curve: P=s(W-V)+V
Quadratic Bezier-Curve: P=t²(A-2B+C)+t(-2A+2B)+A
Because W, V, A, B, and C are points, I could make two equation. I rearranged the first equation to seperate s to solve the equation.
I'm pretty sure i did it correctly, but my intersection was not on the line. So i was wondering and made my own quadratic-Beziercurve by the correct formular and my intersection hits this curve. Now I am wondering what did I wrong?
That is my function:
intersectsWithLineAtT(lineStartPoint, lineEndPoint)
{
let result = []
let A = this.startPoint, B = this.controlPoint, C = this.endPoint, V = lineStartPoint, W = lineEndPoint
if (!Common.isLineIntersectingLine(A, B, V, W)
&& !Common.isLineIntersectingLine(B, C, V, W)
&& !Common.isLineIntersectingLine(A, C, V, W))
return null
let alpha = Point.add(Point.subtract(A, Point.multiply(B, 2)), C)
let beta = Point.add(Point.multiply(A, -2), Point.multiply(B, 2))
let gamma = A
let delta = V
let epsilon = Point.subtract(W, V)
let a = alpha.x * (epsilon.y / epsilon.x) - alpha.y
let b = beta.x * (epsilon.y / epsilon.x) - beta.y
let c = (gamma.x - delta.x) * (epsilon.y / epsilon.x) - gamma.y + delta.y
let underSquareRoot = b * b - 4 * a * c
if (Common.compareFloats(0, underSquareRoot))
result.push(-b / 2 * a)
else if (underSquareRoot > 0)
{
result.push((-b + Math.sqrt(underSquareRoot)) / (2 * a))
result.push((-b - Math.sqrt(underSquareRoot)) / (2 * a))
}
result = result.filter((t) =>
{
return (t >= 0 && t <= 1)
})
return result.length > 0 ? result : null
}
I hope someone can help me.
Lena
The curve/line intersection problem is the same as the root finding problem, after we rotate all coordinates such that the line ends up on top of the x-axis:
which involves a quick trick involving atan2:
const d = W.minus(V);
const angle = -atan2(d.y, d.x);
const rotated = [A,B,C].map(p => p.minus(V).rotate(angle));
Assuming you're working with point classes that understand vector operations. If not, easy enough to do with standard {x, y} objects:
const rotated = [A,B,C].map(p => {
p.x -= V.x;
p.y -= V.y;
return {
x: p.x * cos(a) - p.y * sin(a),
y: p.x * sin(a) + p.y * cos(a)
};
});
Then all we need to find out is which t values yield y=0, which is (as you also used) just applying the quadratic formula. And we don't need to bother with collapsing dimensions: we've reduced the problem to finding solutions in just the y dimension, so taking
const a = rotated[0].y;
const b = rotated[1].y;
const c = rotated[2].y;
and combining that with the fact that we know that Py = t²(a-b+c)+t(-2a+2b)+a we just work out that t = -b/2a +/- sqrt(b² - 4ac))/2a with the usual checks for negative, zero, and positive discriminant, as well as checking for division by zero.
This gives us with zero or more t value(s) for the y=0 intercept in our rotated case, and for the intersection between our curve and line in the unrotated case. No additional calculations required. Aside from "evaluating B(t) to get the actual (x,y) cooordinates", of course.

How to format an array of coordinates to a different reference point

I looked around and I couldn't find any info on the topic... probably because I can't iterate my problem accurately into a search engine.
I'm trying to take raw line data from a dxf, sort it into squares, find the center of each square, number the center, and print the result to pdf.
I have a data structure similar to the following:
[
[{x: 50, y:50}, {x:52, y:52}],
[{x: 52, y:52}, {x:54, y:54}],
[{x: 54, y:54}, {x:56, y:56}]...
]
These coordinates are obtained from parsing a dxf using dxf-parser, which returns an array of objects that describe the path of the line. Four of these combine to make a square, which I segment using
function chunkArrayInGroups(arr, size) {
let result = [];
let pos = 0;
while (pos < arr.length) {
result.push(arr.slice(pos, pos + size));
pos += size;
}
return result;
}
((Size = 4))
This behaves as intended for the most part, except these coordinates were created with the origin in the center of the screen. The pdf library I'm using to create the final document does not use the same coordinate system. I believe it starts the origin at the top left of the page. This made all of my negative values ((Anything to the left of the center of the model)) cut off the page.
To remedy this, I iterate through the array and collect '0 - all x and y values' in a new array, which I find the max of to give me my offset. I add this offset to my x values before plugging them into my pdf creator to draw the lines.
I'm not sure what is causing it, but the output is 'Da Vinci Style' as I like to call it, it's rotated 180 degrees and written backwards. I thought adding some value to each cell would fix the negative issue... and it did, but the data is still with respect to a central origin. Is there a way I can redefine this data to work with this library, or is there some other library where I can graph this data and also add text at specific spots as my case dictates. I would like to continue to use this library as I use it for other parts of my program, but I am open to new and more efficient ideas.
I appreciate your time and expertise!
What it's supposed to look like
Source Picture
"Da Vinci'fied" Result
Current Output
Copy of the code:
const PDFDocument = require('pdfkit');
const doc = new PDFDocument({ autoFirstPage: true })
const DxfParser = require('dxf-parser')
let fileText = fs.readFileSync('fulltest.dxf', { encoding: 'utf-8' })
let data = []
let data2 = []
let data3 = []
let shiftx = []
let shifty = []
let factor = 5
var parser = new DxfParser();
let i = 0
doc.pipe(fs.createWriteStream('test.pdf'));
try {
var dxf = parser.parseSync(fileText);
let array = dxf.entities
array.forEach(line => {
if (line.layer === "Modules") {
data.push(line.vertices)
}
if (line.layer === "Buildings") {
data2.push(line.vertices)
}
if (line.layer === "Setbacks") {
data3.push(line.vertices)
}
let segment = line.vertices
segment.forEach(point => {
shiftx.push(0 - point.x)
shifty.push(0 - point.y)
})
})
let shift = biggestNumberInArray(shiftx)
console.log(shift)
data = chunkArrayInGroups(data, 4)
data.forEach(module => {
let midx = []
let midy = []
module.forEach(line => {
let oldx = (line[1].x + shift) * factor
let oldy = (line[1].y + shift) * factor
let newx = (line[0].x + shift) * factor
let newy = (line[0].y + shift) * factor
doc
.moveTo(oldx, oldy)
.lineTo(newx, newy)
.stroke()
midx.push(oldx + (newx - oldx) / 2)
midy.push(oldy + (newy - oldy) / 2)
})
let centerx = (midx[0] + (midx[2] - midx[0]) / 2)
let centery = (midy[0] + (midy[2] - midy[0]) / 2)
let z = (i + 1).toString()
doc
.fontSize(10)
.text(z, centerx-5, centery-5)
i++
})
data2.forEach(line => {
let oldx = (line[0].x + shift) * factor
let oldy = (line[0].y + shift) * factor
let newx = (line[1].x + shift) * factor
let newy = (line[1].y + shift) * factor
doc
.moveTo(oldx, oldy)
.lineTo(newx, newy)
.stroke()
})
data3.forEach(line => {
let oldx = (line[0].x + shift) * factor
let oldy = (line[0].y + shift) * factor
let newx = (line[1].x + shift) * factor
let newy = (line[1].y + shift) * factor
doc
.moveTo(oldx, oldy)
.lineTo(newx, newy)
.stroke('red')
})
doc.end();
} catch (err) {
return console.error(err.stack);
}
function biggestNumberInArray(arr) {
const max = Math.max(...arr);
return max;
}
function chunkArrayInGroups(arr, size) {
let result = [];
let pos = 0;
while (pos < arr.length) {
result.push(arr.slice(pos, pos + size));
pos += size;
}
return result;
}
After sitting outside and staring at the fence for a bit, I revisited my computer and looked at the output again. I rotated it 180 as I did before, and studied it. Then I imagined it flipped over the y axis, like right off my computer. THAT WAS IT! I grabbed some paper and drew out the original coordinates, and the coordinates the pdf library.
input coords ^ >
output coords v >
I realized the only difference in the coordinate systems was that the y axis was inverted! Changing the lines to
let oldx = (line[1].x + shift) * factor
let oldy = (-line[1].y + shift) * factor
let newx = (line[0].x + shift) * factor
let newy = (-line[0].y + shift) * factor
inverted with respect to y and after the shift, printed correctly! Math wins again hahaha

Calculating the length of a segment in a logarithmic scale

I want to calculate the length of a line for a series of events.
I'm doing this with the following code.
var maxLineLength = 20;
var lineLen = function(x, max) {
return maxLineLength * (x / max);
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
console.log(lineLen(x, max));
});
This works, but I'm using linear scaling, while I'd like to use logarithms, because I don't want small events to become too small numbers when big ones are present.
I modified the lineLen function as you can see below, but - obviously - it doesn't work for events equals to one, because the log of one is zero. I want to show events equals to one (opportunely scaled) and not make them become zero. I also need positive numbers to remain positive (0.1 becomes a negative number)
How should I modify lineLen to use a logarithmic scale?
var maxLineLength = 20;
var lineLen = function(x, max) {
return maxLineLength * (Math.log(x) / Math.log(max));
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
console.log(lineLen(x, max));
});
You can take log(x+1) instead of log(x), that doesn't change the value too much and the ratios are maintained for smaller numbers.
var maxLineLength = 20;
var lineLen = (x, max) => maxLineLength * Math.log(x+1)/Math.log(max+1);
var events = [ 0.1, 1, 5, 20, 50];
var visualizer = function(events){
var max = Math.max.apply(null, events);
return events.reduce((y, x) => {
y.push(lineLen(x, max));
return y;
}, []);
};
console.log(visualizer(events));
You can use an expression like Math.pow(x, 0.35) instead of Math.log(x). It keeps all values positive, and gives the behavior that you want for small ratios. You can experiment with different exponent values in the range (0,1) to find the one that fits your needs.
var maxLineLength = 20;
var exponent = 0.35;
var lineLen = function(x, max) {
return maxLineLength * Math.pow(x/max, exponent);
}
var events = [0, 0.01, 0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
console.log(lineLen(x, max));
});
You could decrement maxLineLength and add one at the end of the calculation.
For values smaller than one, you could use a factor which normalizes all values relative to the first value. The start value is always one, or in terms of logaritmic view, zero.
var maxLineLength = 20,
lineLen = function(max) {
return function (x) {
return (maxLineLength - 1) * Math.log(x) / Math.log(max) + 1;
};
},
events = [0.1, 1, 5, 20, 50],
normalized = events.map((v, _, a) => v / a[0]),
max = Math.max.apply(null, normalized),
result = normalized.map(lineLen(max));
console.log(result);
console.log(normalized);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You are scaling these numbers. Your starting set is the domain, what you end up with is the range. The shape of that transformation, it sounds like, will be either log or follow a power.
It turns out this is a very common problem in many fields, especially data visualization. That is why D3.js - THE data visualization tool - has everything you need to do this easily.
const x = d3.scale.log().range([0, events]);
It's the right to for the job. And if you need to do some graphs, you're all set!
Shorter but not too short; longer but not too long.
Actually I met the same problem years ago, and gave up for this (maybe?).
I've just read your question here and now, and I think I've just found the solution: shifting.
const log = (base, value) => (Math.log(value) / Math.log(base));
const weights = [0, 0.1, 1, 5, 20, 50, 100];
const base = Math.E; // Setting
const shifted = weights.map(x => x + base);
const logged = shifted.map(x => log(base, x));
const unshifted = logged.map(x => x - 1);
const total = unshifted.reduce((a, b) => a + b, 0);
const ratio = unshifted.map(x => x / total);
const percents = ratio.map(x => x * 100);
console.log(percents);
// [
// 0,
// 0.35723375538333857,
// 3.097582209424984,
// 10.3192042142806,
// 20.994247877004888,
// 29.318026542735115,
// 35.91370540117108
// ]
Visualization
The smaller the logarithmic base is, the more they are adjusted;
and vice versa.
Actually I don't know the reason. XD
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="K.">
<title>Shorter but not too short; longer but not too long.</title>
<style>
canvas
{
background-color: whitesmoke;
}
</style>
</head>
<body>
<canvas id="canvas" height="5"></canvas>
<label>Weights: <input id="weights" type="text" value="[0, 0.1, 100, 1, 5, 20, 2.718, 50]">.</label>
<label>Base: <input id="base" type="number" value="2.718281828459045">.</label>
<button id="draw" type="button">Draw</button>
<script>
const input = new Proxy({}, {
get(_, thing)
{
return eval(document.getElementById(thing).value);
}
});
const color = ["tomato", "black"];
const canvas_element = document.getElementById("canvas");
const canvas_context = canvas_element.getContext("2d");
canvas_element.width = document.body.clientWidth;
document.getElementById("draw").addEventListener("click", _ => {
const log = (base, value) => (Math.log(value) / Math.log(base));
const weights = input.weights;
const base = input.base;
const orig_total = weights.reduce((a, b) => a + b, 0);
const orig_percents = weights.map(x => x / orig_total * 100);
const adjusted = weights.map(x => x + base);
const logged = adjusted.map(x => log(base, x));
const rebased = logged.map(x => x - 1);
const total = rebased.reduce((a, b) => a + b, 0);
const ratio = rebased.map(x => x / total);
const percents = ratio.map(x => x * 100);
const result = percents.map((percent, index) => `${weights[index]} | ${orig_percents[index]}% --> ${percent}% (${color[index & 1]})`);
console.info(result);
let position = 0;
ratio.forEach((rate, index) => {
canvas_context.beginPath();
canvas_context.moveTo(position, 0);
position += (canvas_element.width * rate);
canvas_context.lineTo(position, 0);
canvas_context.lineWidth = 10;
canvas_context.strokeStyle = color[index & 1];
canvas_context.stroke();
});
});
</script>
</body>
</html>
As long as your events are > 0 you can avoid shifting by scaling the events so the minimum value is above 1. The scalar can be calculated based on a minimum line length in addition to the maximum line length you already have.
// generates an array of line lengths between minLineLength and maxLineLength
// assumes events contains only values > 0 and 0 < minLineLength < maxLineLength
function generateLineLengths(events, minLineLength, maxLineLength) {
var min = Math.min.apply(null, events);
var max = Math.max.apply(null, events);
//calculate scalar that sets line length for the minimum value in events to minLineLength
var mmr = minLineLength / maxLineLength;
var scalar = Math.pow(Math.pow(max, mmr) / min, 1 / (1 - mmr));
function lineLength(x) {
return maxLineLength * (Math.log(x * scalar) / Math.log(max * scalar));
}
return events.map(lineLength)
}
var events = [0.1, 1, 5, 20, 50];
console.log('Between 1 and 20')
generateLineLengths(events, 1, 20).forEach(function(x) {
console.log(x)
})
// 1
// 8.039722549519123
// 12.960277450480875
// 17.19861274759562
// 20
console.log('Between 5 and 25')
generateLineLengths(events, 5, 25).forEach(function(x) {
console.log(x)
})
// 5
// 12.410234262651711
// 17.58976573734829
// 22.05117131325855
// 25

Why is Firefox 30 times slower than Chrome, when calculating Perlin noise?

I have written a map generator in javascript, using classical perlin noise scripts I have found in various places, to get the functionality I want. I have been working in chrome, and have not experienced any problems with the map. However, when I tested it in firefox, it was incredibly slow - almost hanging my system. It fared better in the nightly build, but still 30 times slower than Chrome.
You can find a test page of it here:
http://jsfiddle.net/7Gq3s/
Here is the html code:
<!DOCTYPE html>
<html>
<head>
<title>PerlinMapTest</title>
</head>
<body>
<canvas id="map" width="100" height="100" style="border: 1px solid red">My Canvas</canvas>
<script src="//code.jquery.com/jquery-2.0.0.min.js"></script>
<script>
$(document).ready(function(){
//Log time in two ways
var startTime = new Date().getTime();
console.time("Map generated in: ");
var canvas = $("#map")[0];
var ctx = canvas.getContext("2d");
var id = ctx.createImageData(canvas.width, canvas.height);
var noiseMap = new PerlinNoise(500);
var startx = 0;
var starty = 0;
var value = 0;
for(var i = startx; i < canvas.width; i++){
for(var j = starty; j < canvas.height; j++){
value = noiseMap.noise(i,j, 0, 42);
value = linear(value,-1,1,0,255);
setPixel(id, i, j, 0,0,0,value);
}
}
ctx.putImageData(id,0,0);
var endTime = new Date().getTime();
console.timeEnd("Map generated in: ");
alert("Map generated in: " + (endTime - startTime) + "milliseconds");
});
function setPixel(imageData, x, y, r, g, b, a) {
index = (x + y * imageData.width) * 4;
imageData.data[index+0] = r;
imageData.data[index+1] = g;
imageData.data[index+2] = b;
imageData.data[index+3] = a;
}
//This is a port of Ken Perlin's "Improved Noise"
//http://mrl.nyu.edu/~perlin/noise/
//Originally from http://therandomuniverse.blogspot.com/2007/01/perlin-noise-your-new-best-friend.html
//but the site appears to be down, so here is a mirror of it
//Converted from php to javascript by Christian Moe
//Patched the errors with code from here: http://asserttrue.blogspot.fi/2011/12/perlin-noise-in-javascript_31.html
var PerlinNoise = function(seed) {
this._default_size = 64;
this.seed = seed;
//Initialize the permutation array.
this.p = new Array(512);
this.permutation = [ 151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
];
for (var i=0; i < 256 ; i++) {
this.p[256+i] = this.p[i] = this.permutation[i];
}
};
PerlinNoise.prototype.noise = function(x,y,z,size) {
if (size == undefined)
{
size = this._default_size;
}
//Set the initial value and initial size
var value = 0.0;
var initialSize = size;
//Add finer and finer hues of smoothed noise together
while(size >= 1)
{
value += this.smoothNoise(x / size, y / size, z / size) * size;
size /= 2.0;
}
//Return the result over the initial size
return value / initialSize;
};
//This function determines what cube the point passed resides in
//and determines its value.
PerlinNoise.prototype.smoothNoise = function(x, y, z){
//Offset each coordinate by the seed value
x += this.seed;
y += this.seed;
z += this.seed;
var orig_x = x;
var orig_y = y;
var orig_z = z;
var X = Math.floor(x) & 255, // FIND UNIT CUBE THAT
Y = Math.floor(y) & 255, // CONTAINS POINT.
Z = Math.floor(z) & 255;
x -= Math.floor(x); // FIND RELATIVE X,Y,Z
y -= Math.floor(y); // OF POINT IN CUBE.
z -= Math.floor(z);
var u = this.fade(x), // COMPUTE FADE CURVES
v = this.fade(y), // FOR EACH OF X,Y,Z.
w = this.fade(z);
var A = this.p[X ]+Y, AA = this.p[A]+Z, AB = this.p[A+1]+Z, // HASH COORDINATES OF
B = this.p[X+1]+Y, BA = this.p[B]+Z, BB = this.p[B+1]+Z; // THE 8 CUBE CORNERS,
return this.lerp(w, this.lerp(v, this.lerp(u, this.grad(this.p[AA ], x , y , z ), // AND ADD
this.grad(this.p[BA ], x-1, y , z )), // BLENDED
this.lerp(u, this.grad(this.p[AB ], x , y-1, z ), // RESULTS
this.grad(this.p[BB ], x-1, y-1, z ))),// FROM 8
this.lerp(v, this.lerp(u, this.grad(this.p[AA+1], x , y , z-1 ), // CORNERS
this.grad(this.p[BA+1], x-1, y , z-1 )), // OF CUBE
this.lerp(u, this.grad(this.p[AB+1], x , y-1, z-1 ),
this.grad(this.p[BB+1], x-1, y-1, z-1 ))));
};
PerlinNoise.prototype.fade = function(t) {
return t * t * t * ( ( t * ( (t * 6) - 15) ) + 10);
};
PerlinNoise.prototype.lerp = function(t, a, b) {
//Make a weighted interpolaton between points
return a + t * (b - a);
};
PerlinNoise.prototype.grad = function(hash, x, y, z) {
h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE
u = h<8 ? x : y; // INTO 12 GRADIENT DIRECTIONS.
v = h<4 ? y : (h==12||h==14 ? x : z);
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
};
PerlinNoise.prototype.scale = function(n) {
return (1 + n)/2;
};
function linear(int, s1, s2, t1, t2)
{
t = [t1, t2];
s = [s1, s2];
rangeS = s1 - s2;
rangeT = t1 - t2;
if((s1 < s2 && t1 > t2) || (s1>s2 && t1<t2))
{
interpolated = ((int - s1) / rangeS*rangeT) + t1;
}
else
{
interpolated = ((int - s1) / rangeS)*rangeT + t1;
}
if(interpolated > Math.max.apply(Math, t))
{
interpolated = Math.max.apply(Math, t);
}
if(interpolated < Math.min.apply(Math, t))
{
interpolated = Math.min.apply(Math, t);
}
return interpolated;
}
</script>
</body>
</html>
I get 33 ms on Chrome, and 1051ms on Firefox 24 Nightly
The results are inconsistent though. Sometimes the Nightly results is as fast as chrome...
Do you know why there is so much variation in this particular instance?
I don't know enough about the theory of perlin noise to try optimizing the code, so don't know what to do.
I have found the culprit. The slowdown occurs when I have Firebug enabled. That extension must weigh it down.

Categories