Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div>

<canvas id="mrcanvas">

</canvas>

</div>

<div>
	<div class="mrtextblock">
		<div>
		  <span>Use Uniform Grid : </span><input type="checkbox" id="toggleMode">
		</div>
		<div>
		  <span>Toggle Lines: </span><input type="checkbox" id="toggleLines" checked="checked">
		</div>
	</div>
	<div class="mrtextblock" >
    <div>
      Drag the orange circles around!
    </div>
    <div id="statistics">
    </div>
	</div>
</div>

            
          
!
            
              #mrcanvas {
	width: 512px;;
	height: 512px;
}

span {
	width: 140px;
	display: inline-block;
}

.mrtextblock {
	float: left;
	width: 250px;
}
            
          
!
            
              //helper method for browsers from stone age
Math.hypot = Math.hypot || function(x, y) {
  return Math.sqrt(x*x + y*y);
};

//magic flags
var UseQuadTree = true;
var ShowQuadLines = true;

//root of quadtree
var Root;
//tick helps us not need to rebuild the tree every time, if tick isn't most recent we can act like it isn't visited
var Tick = 0;
//uniform quadrilaterals
var Quads = [];

//magic constants
var ATOM = 8;
var SIGHT = 64;
var CANVASSIZE = 512;
var ORANGE = '#FF6600';
var WHITE = '#FFFFFF';
var BLACK = '#000000';
var GREY = '#999999';
var DARKGREY = '#444444';
var YELLOW = '#FFFF00';

var c=document.getElementById("mrcanvas");
c.width = CANVASSIZE;
c.height = CANVASSIZE;
//prevent right click menu
c.oncontextmenu = function (e) {
    e.preventDefault();
};

//option handlers
var ToggleMode = function() {
	UseQuadTree = !UseQuadTree;
	RenderScene();
}

var ToggleLines = function() {
	ShowQuadLines = !ShowQuadLines;
	RenderScene();
}

var statsBlock = document.getElementById("statistics");

var UpdateStatistics = function(number) {
	statsBlock.innerHTML = "" + number + " quads rendered.";
}

var checkbox = document.getElementById("toggleMode");
checkbox.addEventListener('click', ToggleMode);

var checkbox = document.getElementById("toggleLines");
checkbox.addEventListener('click', ToggleLines);

//initialize view nodes
var NodeVertices = []
for(var i = 0; i < 25; i++) {
	NodeVertices.push({
		x: 100 + (i * 25) % 125,
		y: 100 + Math.floor(i / 5) * 25
	});
}

var DraggingNode = null;

var MouseDown = function(e) {
	var x = e.pageX;
	var y = e.pageY;
	var vertex = { x: x - c.offsetLeft, y: y - c.offsetTop};
	
	//left click
	if(e.button === 0) {
		var node = GetNodeSelection(vertex);
		//check if grabbing a node
		if(node != null) {
			DraggingNode = node;
		}
	}
}

var MouseUp = function(e) {
	var x = e.pageX;
	var y = e.pageY;
	var vertex = { x: x - c.offsetLeft, y: y - c.offsetTop};

	if(DraggingNode != null) {
		DraggingNode.x = vertex.x;
		DraggingNode.y = vertex.y;
		DraggingNode = null;
		RenderScene();
	}
}

var MouseMove = function(e) {
	var x = e.pageX;
	var y = e.pageY;
	var vertex = { x: x - c.offsetLeft, y: y - c.offsetTop};

	if(DraggingNode != null) {
		DraggingNode.x = vertex.x;
		DraggingNode.y = vertex.y;
		RenderScene();
	}
}

var GetNodeSelection = function(vertex) {
	var selection = null;
	for(var i = 0; i < NodeVertices.length; i++) {
		if(Math.hypot(NodeVertices[i].x - vertex.x, NodeVertices[i].y - vertex.y) < 11) {
			selection = NodeVertices[i];
		}
	}
	return selection;
}

c.addEventListener("mousedown", MouseDown, false);
c.addEventListener("mousemove", MouseMove, false);
c.addEventListener("mouseup", MouseUp, false);
var Ctx=c.getContext("2d");
Ctx.lineWidth = 1;

var RenderScene = function() {
	var array = [];
	if(UseQuadTree) {
		RevealQuadTree(NodeVertices);
		Root.GetFogInfo(array)
	} else {
		RevealGrid(NodeVertices);
		GetGridFogInfo(array);
	}

	Ctx.clearRect(0, 0, c.width, c.height);
	for(var i = 0; i < array.length; i++) {
		DrawRectangle(array[i]);
	}
	
	DrawNodes();
	UpdateStatistics(array.length);
}

var DrawRectangle = function(quad, highlight) {
	Ctx.beginPath();

	Ctx.moveTo(quad.minx, quad.miny);
	Ctx.lineTo(quad.maxx, quad.miny);
	Ctx.lineTo(quad.maxx, quad.maxy);
	Ctx.lineTo(quad.minx, quad.maxy);
	Ctx.lineTo(quad.minx, quad.miny);

	Ctx.closePath();
	
	if(highlight) {
		Ctx.strokeStyle = YELLOW;
	} else {
		Ctx.strokeStyle = GREY;
	}
	if(quad.revealedTick == Tick && quad.revealedStatus == "FullyInBounds") {
		Ctx.fillStyle = WHITE;
	} else {
		Ctx.fillStyle = DARKGREY;
	}
	
	Ctx.fill();
	if(ShowQuadLines) {
		Ctx.stroke();
	}
}

var DrawNodes = function() {
	for(var i = 0; i < NodeVertices.length; i++) {
		Ctx.beginPath();
		Ctx.strokeStyle = BLACK;
		Ctx.fillStyle = ORANGE;
		Ctx.arc(NodeVertices[i].x, NodeVertices[i].y, 10, 0, 2 * Math.PI, false);
		Ctx.stroke();
		Ctx.fill();
		Ctx.closePath();
	}
}

// var DrawText = function(text, y) {
	// var x = 30;
	// Ctx.font = "bold 20px Arial";
	// Ctx.strokeStyle = 'black';
	// Ctx.lineWidth = 3;
	// Ctx.strokeText(text, x, y);
	// Ctx.fillStyle = 'white';
	// Ctx.fillText(text, x, y);
// }

//quadtree object 
var QuadTree = function(minx, miny, maxx, maxy) {
	this.minx = minx;
	this.miny = miny;
	this.maxx = maxx;
	this.maxy = maxy;
	this.children = [];
	this.revealedStatus = "OutOfBounds";
	this.revealedTick = -1;
}
//v for vertexxa
QuadTree.prototype.ContainsPoint = function(v) {
	return (v.x <= maxx && v.x > minx && x.y <= maxy && v.y > miny);
}
//check if min size
QuadTree.prototype.IsAtom = function() {
	return this.maxx - this.minx <= ATOM;
}
//returns all OutOfBounds and FullyInBounds quads as well as Atomic quads
QuadTree.prototype.GetFogInfo = function(array) {
	if(Tick != this.revealedTick) {
		array.push(this);	//then obviously fog - not queried at all
		return;
	} else {
		switch (this.revealedStatus) {
			case "OutOfBounds":
				array.push(this);	//then fog
				return;
			case "FullyInBounds":
				array.push(this);
				return;
			case "PartiallyInBounds":
				if(this.IsAtom()) {
					array.push(this);	//then fog
					return;
				} else {
					for(var i = 0; i < 4; i++) {
						this.children[i].GetFogInfo(array);
					}
				}
		}
	}
}
QuadTree.prototype.Reveal = function(v, radius)
{
	//already fully revealed this turn
	if(this.revealedTick == Tick && this.revealedStatus == "FullyInBounds") {
		return;
	}
	
	//set default state (unrevealed) if not already looked at this turn
	if(this.revealedTick != Tick) {
		this.revealedStatus = "OutOfBounds";
	}
	this.revealedTick = Tick;
	
	//reveal some radius r around point v
	var thisBounds = this.InBounds(v, radius);
	
	switch (thisBounds) {
		case "FullyInBounds":
			this.revealedStatus = "FullyInBounds";
			return;
		case "OutOfBounds":
			//default is already set so don't change
			return;
		case "PartiallyInBounds":
			this.revealedStatus = "PartiallyInBounds";
			if(!this.IsAtom()) {
				if(this.children.length == 0) {
					this.MakeChildren();
				}
				this.RevealChildren(v, radius);
          //check if all children are fully revealed - if so we can mark this as fully revealed
          var allRevealed = true;
          for(var i = 0; i < this.children.length; i++) {
            allRevealed &= (this.children[i].revealedStatus == "FullyInBounds");
          }
          if(allRevealed) {
            this.revealedStatus = "FullyInBounds";
          }
			}
	}
}
QuadTree.prototype.RevealChildren = function(v, radius) {
	this.children[0].Reveal(v, radius);
	this.children[1].Reveal(v, radius);
	this.children[2].Reveal(v, radius);
	this.children[3].Reveal(v, radius);
}
QuadTree.prototype.MakeChildren = function() {
	//minx, miny, maxx, maxy
	var halfSize = (this.maxx - this.minx)/2;
	this.children[0] = new QuadTree(this.minx, this.miny, this.minx + halfSize, this.miny + halfSize);
	this.children[1] = new QuadTree(this.minx + halfSize, this.miny, this.maxx, this.miny + halfSize);
	this.children[2] = new QuadTree(this.minx, this.miny + halfSize, this.minx + halfSize, this.maxy);
	this.children[3] = new QuadTree(this.minx + halfSize, this.miny + halfSize, this.maxx, this.maxy);
}
QuadTree.prototype.InBounds = function(v, radius)
{
	//i think this helps with not branching
	var rr = square(radius);
	var minx2 = square(v.x - this.minx);
	var maxx2 = square(v.x - this.maxx);
	var miny2 = square(v.y - this.miny);
	var maxy2 = square(v.y - this.maxy);

	//this checks corners if every corner is in bound then fully in bound
	var one = minx2 + miny2 < rr;
	var two = minx2 + maxy2 < rr;
	var three = maxx2 + miny2 < rr;
	var four = maxx2 + maxy2 < rr;

	if(one && two && three && four)
	{
		return "FullyInBounds";
	}
		
	//get centre of quad
	var cx = (this.maxx + this.minx) / 2;
	var cy = (this.maxy + this.miny) / 2;
	var cr = 0.71 * (this.maxx - this.minx);
	
	//furthest the center of a circle and a square can be while still overlapping 
	//is radius of circle + (0.71 * sidelength of square)
	if(Math.hypot(v.x - cx, v.y - cy) < (cr + radius)) {
		return "PartiallyInBounds";
	}
		
	return "OutOfBounds";
}


//quad for uniform grid
var Quad = function(minx, miny, maxx, maxy) {
	this.minx = minx;
	this.miny = miny;
	this.maxx = maxx;
	this.maxy = maxy;
	this.revealedStatus = "OutOfBounds";
	this.revealedTick = -1;
}
Quad.prototype.InBounds = function(v, radius)
{
	//i think this helps with not branching
	var rr = square(radius);
	var minx2 = square(v.x - this.minx);
	var maxx2 = square(v.x - this.maxx);
	var miny2 = square(v.y - this.miny);
	var maxy2 = square(v.y - this.maxy);

	//this checks corners if every corner is in bound then fully in bound
	var one = minx2 + miny2 < rr;
	var two = minx2 + maxy2 < rr;
	var three = maxx2 + miny2 < rr;
	var four = maxx2 + maxy2 < rr;

	if(one && two && three && four)
	{
		return "FullyInBounds";
	}
		
	//get centre of quad
	var cx = (this.maxx + this.minx) / 2;
	var cy = (this.maxy + this.miny) / 2;
	var cr = 0.71 * (this.maxx - this.minx);
	
	//furthest the center of a cirle and a square can be while still overlapping 
	//is raidus of circle + 0.71 x sidelength of square
	if(Math.hypot(v.x - cx, v.y - cy) < (cr + radius)) {
		return "PartiallyInBounds";
	}
		
	return "OutOfBounds";
}
Quad.prototype.Reveal = function(v, radius) {
	if(this.revealedTick == Tick && this.revealedStatus == "FullyInBounds") {
		return;
	}
	if(this.revealedTick != Tick) {
		this.revealedStatus = "OutOfBounds";
	}
	this.revealedTick = Tick;
	this.revealedStatus = this.InBounds(v, radius);
}
Quad.prototype.ContainsPoint = function(v) {
	return (v.x <= maxx && v.x > minx && x.y <= maxy && v.y > miny);
}

var GetGridFogInfo = function(array) {
	for(var i = 0; i < Quads.length; i++) {
		/* if(Quads[i].revealedStatus != "FullyInBounds") {
			array.push(Quads[i]);
		} */
		array.push(Quads[i]);
	}
}

var square = function(n)
{
	return n*n;
}

var RevealQuadTree = function(entities) {
	Tick++;
	for(var i = 0; i < entities.length; i++) {
		Root.Reveal(entities[i], SIGHT);
	}
}

var RevealGrid = function(entities) {
	Tick++;
	for(var i = 0; i < entities.length; i++) {
		for(var j = 0; j < Quads.length; j++) {
			Quads[j].Reveal(entities[i], SIGHT);
		}
	}
}

var Initialize = function() {
//instantiate quadtree
Root = new QuadTree(0, 0, CANVASSIZE, CANVASSIZE);

//instantiate uniform grid
for(var x = 0; x < CANVASSIZE; x += ATOM) {
	for(var y = 0; y < CANVASSIZE; y += ATOM) {
		var minx = x;
		var miny = y;
		var maxx = x + ATOM;
		var maxy = y + ATOM;
		Quads.push(new Quad(minx, miny, maxx, maxy));
	}
}

RenderScene();

}

window.onload = function() {
	Initialize();
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console