Author Archives: godlikemouse

Drawing on Textures in ThreeJS

If you’re an avid user of ThreeJS you have more than likely at some point run into the situation where you need to either create a texture from scratch for the point of coloring it, or have had the need to update/draw on a texture for one reason or another.  The following will walk you through what is needed to accomplish this.

First, start by creating an in memory canvas object that we will use to draw on.  This will eventually be transformed into a texture object.

//create in memory canvas
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext("2d");

 

For this example, I’m creating a simple 100×100 pixel image and retrieving the 2d context which we will next use for performing that actual modification of the image.

//paint the image red
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 100, 100);

 

Here we’re setting the fill color to red and painting the entire image.  Next, let’s convert our in memory canvas object into an image.

//create image from canvas
var image = new Image();
image.src = canvas.toDataURL();

 

Finally, let’s take our new image and create a texture object which can be applied to a material.

//create new texture
var texture = new THREE.Texture(image);
texture.anisotropy = 4;
texture.needsUpdate = true;
 
//apply texture to a material, go forth and be merry

 

That’s really all there is to it, you can make the context draw lines, rects, etc. onto the in memory canvas until your heart’s content.  For convenience, the following is the entire code example wrapped up into one.

//create in memory canvas
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext("2d");
 
//paint the image red
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 100, 100);
 
//create image from canvas
var image = new Image();
image.src = canvas.toDataURL();
 
//create new texture
var texture = new THREE.Texture(image);
texture.anisotropy = 4;
texture.needsUpdate = true;
 
//apply texture to a material, go forth and be merry

Getting Windows 10 Home Remote Desktop Working

Windows 10 Home edition by default will not allow you to have inbound remote desktop connections.  Regardless of any settings you may find to the contrary, turning off your firewall, etc. there will just not be anything you can do directly at the user level to enable it.  All is not lost however, there is a very simple fix that you can apply to enable this functionality.

First download RDPWrap at: https://github.com/stascorp/rdpwrap/releases

You want to download the release which takes a form like “RDPWrap-v1.6.zip” for example.

Next, unpack the zip file to a directory and find the file entitled “install.bat”, right click and choose “Run as Administrator”, grant the permission when prompted and let the batch file run its course.

After the installation completes, execute the file “RDPCheck” and ensure that the “Wrapper state”, “Service state” and “Listener state” status are all green.  If they are, then you’re good to go, change whatever configuration settings you would like and remote in.

RDPCheck

If you find that any of the status states are red, such as the “Listener state” for example, ensure that your firewall is not blocking by turning your firewall off just for a quick test and try the “RDPCheck” again.  If you still find that there is a status issue, file the file “update.bat”, right click and choose “Run as Administrator”, grant the permission when prompted and let the batch file run its course.  Once the update has completed, try running the “RDPCheck” check again, you should be good to go.

New Rubik’s Cube jQuery ThreeJS WebGL Plugin

I have previously released a jQuery Rubik’s cube plugin comprised of only HTML, JavaScript and CSS.  Although pretty nifty, there were a few issues with regards to support from some browsers, most notably Firefox and Internet Explorer.  I decided to recreate the plugin using WebGL.  The result is my jquery.cube.threejs.js plugin. As seen below.

The plugin code is available here: https://github.com/godlikemouse/jquery.cube.threejs.js

See the Pen jQuery ThreeJS Rubik’s Cube by Jason Graves (@godlikemouse) on CodePen.

This plugin utilizes standard cube notation, both modern and old to execute moves. For example, the moves executed by the 3×3 cube above are utilizing the following notation:

x (R’ U R’) D2 (R U’ R’) D2 (R U R’) D2 (R U’ R’) D2 (R U R’) D2 (R U’ R’) D2 R2 x’

This algorithm is being passed to the cube plugin by way of the execute() method or data-moves attribute.

This plugin currently supports a number of configuration options that can be passed at instantiation time including, cube face colors, animation delay time with more to come shortly.

This incarnation of the plugin also supports cube sizes of 2×2 up to 9×9 with no issues.  Cubes larger than 9×9 may see some degradation in frame rates depending on the speed of the client devices.

For more information on this plugin or to view the source please visit: https://github.com/godlikemouse/jquery.cube.threejs.js

Build Your Own Private Gaming Cloud

I’ve run into several occasions where I’ve purchased a game and there’s no support for cloud save storage. Back in the day this was the norm, but being that most gaming services such as Steam, Origin, etc. offer some form of cloud game saving backup and storage; I find myself a bit spoiled by these niceties and get irritated when I purchase a game where this is not provided.

I have come up with a very simple and fast way to implement your own gaming cloud storage for games that don’t support it out of the box and it requires no programming whatsoever.

So let’s get started.

Cloud Storage Client

The first thing you’re going to want to do is setup and account with an online storage service that has an installable client for handling the cloud synchronization, for my example I’ll be using Google Drive on Windows, but you can use any cloud storage client you prefer, Dropbox, Box, etc.

First download and install the client software.
GoogleDriveDownload

Local and Remote Folder Setup

Next you’ll need to locate the game save location on your machine. For my example, I’ll be using GTA V purchased through the Rockstar Social Club.

The game save location for this game is:

C:\Users\<username>\Documents\My Games\Rockstar Games\GTA V

(Please note that the <username> notation should be replaced with your actual username.)

GTAVDirectory

Next, let’s setup a folder in our cloud service provider specifically for gaming. I have mine setup as “Gaming” located at:

C:\Users\<username>\Google Drive\Gaming

GamingFolder

Now what you’re going to want to do is copy the “GTA V” directory first to a location where nothing can happen to it (just to be safe, I put mine on the Desktop), then copy the “GTA V” folder to your “Gaming” folder located under your storage service folder:

C:\Users\<username>\Google Drive\Gaming\GTA V

GamingGTAVFolder

Next, make sure you’ve already copied the original game save folder someplace other than your storage service folder just to be safe, then remove the original “GTA V” directory located at:

C:\users\<username>\Documents\My Games\Rockstar Games\GTA V

GTAVDirectory

Finally, create a symbolic link to the storage service folder with the exact name of the game directory name. If you’re using Windows please follow the “For Windows 7 or Higher” section, if you’re using Mac OS or Linux please follow the “Mac OS or Linux” section.

For Windows 7 or Higher

First click the windows start button (or hit the windows key) and type “cmd”. Next, right click on the “cmd” entry in the start menu and select “Run as Administrator”.

RunCmdAsAdmin

Next change directory to the directory above your original game save location, for example:

cd "C:\Users\<username>\Documents\My Games\Rockstar Games"

Finally create the symbolic link for the game to the storage service folder:

mklink /D "GTA V" "C:\users\\Google Drive\Gaming\GTA V"

You should see something like this when the command is complete:

symbolic link create for GTA V <<===>> c:\Users\<username>\Google Drive\Gaming\GTA V

For Mac OS X or Linux

Open a terminal (Mac: command + space and type “term”) and change to your game directory:

cd /Users/<username>/Documents/Games

Create the symbolic link for the game to the storage service folder:

ln -s /Users/<username>/Google\ Drive/Gaming/GTA\ V GTA\ V

Test and Play

Finally, test and make sure this works by launching the game and verifying that your game has loaded correctly. Once your sure all your game save content is correct, feel free to remove the safe location back copy folder (In my example this is the “GTA V” folder I copied to the desktop).

Repeat the symbolic link creation process on all the the machines you want to be able to seamlessly access your games on and you’ll never have to worry about your game saves again.

How To: Hulu.com and Arch Linux

Hey everyone, I’ve figured out how to get Hulu.com working on Arch Linux today. Here’s what I did in case anyone else needs help:

First install pipelight:

user@computer:$ yaourt -S pipelight

Next, if you don’t already have it install firefox:

user@computer:$ sudo pacman -S firefox

Next, update and configure pipelight:

user@computer:$ sudo mkdir /root/.gnupg
user@computer:$ sudo pipelight-plugin --update

Next, enable the flash plugin:

user@computer:$ sudo pipelight-plugin --enable flash

Next, add the plugins to firefox:

user@computer:$ sudo pipelight-plugin --create-mozilla-plugins

Lastely, make sure you have hal installed:

user@computer:$ yaourt -S hal-flash-git
user@computer:$ yaourt -S hal-info

Once you’ve completed the steps above, completely kill of firefox (Super+Q), then restart and browse to Hulu.com, you should be able to watch it with no problems.

New Rubik’s Cube jQuery Plugin

I consider myself an avid speed cuber. Not world class, but fast enough and not too obsessed with it. That being said all the sites I’ve seen in the past with references to algorithms all seem to use really clunky client side Java or Flash plugins to handle the demonstration of moves.  I wanted to create a simple to implement jQuery plugin that utilizes the browser’s built in features to do the same thing.  The result is my jquery.cube.js plugin. As seen below.

The plugin code is available here: https://github.com/godlikemouse/jquery.cube.js

 

See the Pen jQuery and CSS Implemented Rubik’s Cube by Jason Graves (@godlikemouse) on CodePen.

This plugin utilizes standard cube notation, both modern and old to execute moves. For example, the moves executed above are utilizing the following notation:

x (R’ U R’) D2 (R U’ R’) D2 (R U R’) D2 (R U’ R’) D2 (R U R’) D2 (R U’ R’) D2 R2 x’

This algorithm is being passed to the cube plugin by way of the execute() method.

This plugin currently supports a number of configuration options that can be passed at instantiation time including, cube face colors, animation delay time with more to come shortly.

For more information on this plugin or to view the source please visit: https://github.com/godlikemouse/jquery.cube.js

Responsive CSS Truncate and Ellipsis

We’ve all run into situations where we need to truncate text due to length constraints.  Most of the time this simply requires a truncation function which determines the maximum length of text and if the string exceeds that length, truncates it and adds an ellipsis (“…”).  But what about when we are developing responsive web applications that require text to be truncated according to the current device screen or browser size.  Luckily CSS3 supports a text-transform property called “ellipsis”, this however also requires that the bounding box defined with an overflow and a definite width and height.  Or does it…?

I’ve found an interesting way to implement CSS text truncation in a responsive setting that can be used with responsive layouts such as Pure, Bootstrap, etc.

The following code creates a single line responsive truncate and ellipsis behavior.

.truncate-ellipsis {
    display: table;
    table-layout: fixed;
    width: 100%;
    white-space: nowrap;
}
 
.truncate-ellipsis > * {
    display: table-cell;
    overflow: hidden;
    text-overflow: ellipsis;
}

 

<div class="truncate-ellipsis">
    <span>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam porta tortor vitae nisl tincidunt varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut vel ullamcorper tortor. Nullam vel turpis a augue tempor posuere vel quis nibh. Nam ultrices felis turpis, at commodo ipsum tristique non. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse in accumsan dui, finibus pharetra est. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae velit eu dui rutrum pellentesque vel imperdiet sem. Morbi ut lacinia lacus, in commodo nibh. Sed cursus ante ut nunc molestie viverra.
    </span>
</div>

 

This works by taking a parent element, in this case a “div” with the class “truncate-ellipsis” and turning it into a display type table with a fixed table layout. Its child element, in this case a “span” is transformed into a table cell with the overflow set to hidden and the text-transform property set to ellipsis.  This of course can be modified to suit specific needs of height and container size and should act as a pretty good starting point for basic implementation.

Storing And Retrieving Objects In HTML5 Local Storage

I’ve recently had the need to store information using HTML5’s local storage API.  To my surprise the API itself is geared toward only letting you store strings.  That being said I needed to store and retrieve information in a way that would make it easy to retain types as well as store complete objects.  The following is the approach I used which should help those of you unfamiliar with HTML5 local storage get up to speed on how to use it, as well as introduce a possibly not so obvious way to store complete object information as well as retain basic types.

Basic storage of information is simple.

localStorage["mykey"] = "myvalue";

Retrieval is just as easy.

var myvalue = localStorage["mykey"];

But what about actual types? Hmmm….

localStorage["mykey"] = 42;
var myvalue = localStorage["mykey"]; //returns the string "42"
 
//wait a minute...
 
localStorage["mykey"] = {};
var myvalue = localStorage["mykey"]; //returns the string "[object Object]"

Well crap! I’ve lost my input type and retrieved a string on the other side.  What’s a coder to do?  How about we make it retain our input types, not only that, let’s make it so we can store object types as well.

jQuery has some nice JSON parsing utilities among other things, let’s incorporate that along with a way to serialize objects into JSON strings.  First we’ll need a JSON serializer, better known as a stringifier (No, I didn’t make that up.  That’s actually what it’s called.)

Here’s a simple method which can be used to extend jQuery and allow objects to be stringified.

jQuery.extend({
stringify : function stringify(obj) {
	if(JSON && JSON.stringify)
		return JSON.stringify(obj);
 
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"' + obj + '"';
			return String(obj);
	} else {
		// recurse array or object
		var n, v, json = [], arr = (obj && obj.constructor == Array);
 
		for (n in obj) {
			v = obj[n];
			t = typeof(v);
			if (obj.hasOwnProperty(n)) {
				if (t == "string") v = '"' + v + '"'; else if (t == "object" && v !== null) v = jQuery.stringify(v);
				json.push((arr ? "" : '"' + n + '":') + String(v));
			}
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
}
});

The above code is a very simple stringifier.  There are far more complex ones out there if you do a little searching, but I’ve been using this one for quite a while and it has always suited my needs.  Unfortunately however, I don’t remember where I originally found this code.  I didn’t write it, full credit goes to the original author (and if you know who that is please let me know and I’ll add an ownership clause).

Now, if we combine the use of our new stringifier and the use of jQuery’s own $.parseJSON, we should be in business.  Let’s give it a try.

var myvalue = {
first: "Bob",
last: "Dobalina",
age: 52
};
 
//let's store it
localStorage["mykey"] = $.stringify(myvalue);
 
//now let's retrieve it
myvalue = $.parseJSON( localStorage["mykey"] ); //returns actual JSON object

Perfect, now all our types are intact, we can store and retrieve objects ad nauseam, the world is once again a perfect place, birds are singing, no they don’t use Photoshop – super models really look like that and everything that tastes good is actually good for you.  Let’s verify our object types.

var first = myvalue.first; //returns "Bob"
var last = myvalue.last; //returns "Dobalina"
var age = myvalue.age; //returns 52

It’s worth being said that this point as well that local storage does have a size limitation of 5MB based on origin (which if you’re unfamiliar with is scheme + hostname + port).  So keep that in mind as you move forward with storing local information.  Hope this helps and thanks for swinging by.

Never Use HTML Tables, Ever!

I know what you’re probably thinking, come on man…there are legitimate reasons for using tables on occasion, to display tabular data, etc.  Well, yes and no.  Agreed, there is the need for table like formatting and functionality however, tables bring with them some very bizarre remnants with regard to CSS, JavaScript interaction (especially with adding and removing rows, try a google search, you’ll see what I’m talking about) as well as a few other unmentionables used by a few ambitious developers out there.  So what do we do, never use them again…ever!  “What?  Wha…what is this nonsense you speak of?” one might say and here’s my answer.

We don’t need to use tables, we can get table like functionality cleanly with none of the hassles of using true HTML tables especially with regard to JavaScript and CSS, and here’s how.

Replace all HTML tables with CSS styled equivalents.  Let’s take a look at a properly formatted HTML table, then we’ll look at how to replace it.  Consider the following:

<table>
    <thead>
        <tr>
            <th>Heading 1</th>
            <th>Heading 2</th>
            <th>Heading 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Cell 1</td>
            <td>Row 1 Cell 2</td>
            <td>Row 1 Cell 3</td>
        </tr>
        <tr>
            <td>Row 2 Cell 1</td>
            <td>Row 2 Cell 2</td>
            <td>Row 2 Cell 3</td> 
        </tr>
    </tbody>
</table>

 

As we can see above this is a basic table using the HTML table tags along with thead and tbody.

Now, let’s take a look at the replacement:

First the markup:

<div class="table">
    <div class="thead">
        <div class="table-row">
            <div class="table-heading">
                <div class="table-cell">Heading 1</div>
                <div class="table-cell">Heading 2</div>
                <div class="table-cell">Heading 3</div>
            </div>
        </div>
    </div>
    <div class="tbody">
        <div class="table-row">
            <div class="table-cell">Row 1 Cell 1</div>
            <div class="table-cell">Row 1 Cell 2</div>
            <div class="table-cell">Row 1 Cell 3</div>
        </div>
        <div class="table-row">
            <div class="table-cell">Row 2 Cell 1</div>
            <div class="table-cell">Row 2 Cell 2</div>
            <div class="table-cell">Row 2 Cell 3</div>
        </div>
    </div>

Next, the style:

div.table {
    display: table;
}
 
div.table > div.thead {
    display: table-header-group;
}
 
div.table > div.tbody {
    display: table-row-group;
}
 
div.table > div.thead > div.table-row,
div.table > div.tbody > div.table-row {
    display: table-row;
}
 
div.table > div.thead > div.table-row > div.table-heading {
    display: table-cell;
    font-weight: bold;
}
 
div.table > div.tbody > div.table-row > div.table-cell {
    display: table-cell;
}

Now we have all the functionality of a table with none of the CSS styling issues and interacting with JavaScript is straight forward and simple.  The only real issue I see with this approach is the “div soup” that is seen in place of individual tags.  Additional styling attributes such as border, cell padding and cell spacing can be controlled using standard CSS properties such as border, padding, etc.

I’ve been implementing and using this approach for quite some time now with no issues and plenty of benefits.  Feel free to let me know your feelings about this approach.  Thanks.

D3 and jQuery Interoperability

D3 and jQuery utilize distinctly different approaches to node manipulation and internal array storage. However, there are mechanisms available for converting between D3 and jQuery, and vice versa.

D3 and jQuery Internals

Let’s assume the following HTML structure:

<div class="test-node">Test One</div>
<div class="test-node">Test Two</div>
<div class="test-node">Test Three</div>
<div class="test-node">Test Four</div>

Now let’s retrieve the “test-node” elements with jQuery:

var testNodes = $(".test-node");
console.log(testNodes);

Console Log

As can be seen above, jQuery stores the selected elements in a first level array, making elements accessible by testNodes[0…3] as expected.  Now let’s examine the D3 equivalent:

var testNodes = d3.selectAll(".test-node");
console.log(testNodes);

Console Log

When using D3, the selected elements get stored in a second level array making the elements accessible by testNode[0][0…n].

Converting from jQuery to D3

var $testNodes = $(".test-node");  //jquery
var testNodes = d3.selectAll( $testNodes.toArray() ); //d3
console.log(testNodes);

Console Log

The above first retrieves the nodes using standard jQuery selector syntax.  Next the “toArray()” method is called returning the native array of selected elements.  Finally the “d3.selectAll()” method is invoked using the native array as the argument.  This forces the native element array into the second level array of D3.

Converting from D3 to jQuery

var testNodes = d3.selectAll(".test-node");
var $testNodes = $(testNodes[0]);
console.log($testNodes);

Console Log

The above first retrieves the nodes using D3 selector syntax.  Next the first level D3 array is used as the argument passed into the jQuery selector.

Class Addition/Removal

Adding and removing a class in jQuery is pretty straightforward:

$(".test-node").addClass("selected"); //add class "selected"
$(".test-node").removeClass("selected"); //remove class "selected"

The same performed in D3 is performed using the following:

d3.selectAll(".test-node").classed("selected", true); //add class "selected"
d3.selectAll(".test-node").classed("selected", false); //remove class "selected"

Data/Datum

D3 has a very elegant data system whereby information can be bound to elements by use of the “datum()” method.

D3 Datum

Let’s examine the following:

var nodes = d3.selectAll(".test-node")
    .datum({key: "hello", value: "world"})
    .append("span");
 
console.log(nodes);

Console Log

The above example selects all of the “.test-node” div classed elements utilizing D3, initializes a data structure/object and passes this structure/object to the “span” elements which get appended to all the matching “.test-node” div classed elements.  This “datum()” method passes the data structure/object to the “span” elements using a property called “__data__”.  As displayed above, the __data__ property has the structure of:

__data__: {
    key: "hello",
    value: "world"
}

The “__data__” property can be accessed directly using second level array syntax (ie. d3.selectAll(“span”)[0][0…n].__data__) or it can be utilized as a default argument passed into nearly all D3 selector instance methods.  Let’s examine an instance method where this takes place:

var nodes = d3.selectAll(".test-node")
    .datum({key: "hello", value: "world"})
    .append("span")
    .text(function(d){
        return d.key + " " + d.value;
    });

In the above example, the only difference from the previous example is the instance method “text()”, whereby the argument passed is a function.  This function defines an argument “d” which D3 passes to these type of instance methods automatically.  The “d” argument being the actual data/datum used to initialize the “span” elements.  The body of the text function returns the string “hello world” using the data/datum, thusly setting the text of the “span” elements to “hello world”.

jQuery Data

jQuery has a simple mechanism for adding arbitrary data to elements by use of the “data()” method.  Let’s examine the following:

var nodes = $(".test-node")
    .append("span")
    .data("datum", {key: "hello", value: "world"});
 
console.log(nodes);
console.log($.cache);

Console Log

In the above example, the “.test-node” elements are retrieved, “span” elements are appended and the datum {key: “hello”, value: “world”} is added to the data.  The console output reveals that the datum is stored in the $.cache in jQuery.

Exchanging D3 Datum with jQuery

Now that we’ve seen how both D3 and jQuery store data/datum, let’s exchange D3 datum with jQuery:

//D3
var nodes = d3.selectAll(".test-node")
    .datum({key: "hello", value: "world"})
    .append("span");
 
console.log(nodes);
 
//jQuery
var $nodes = $(nodes[0]);
$nodes.each(function(){
    $(this).data("datum", $(this).prop("__data__"));
});
 
console.log($nodes);
console.log($.cache);

Console LogIn this example, we first select the “.test-node” classed elements using D3, append “span” elements using the datum/data specified.  Next, we create a jQuery selector using the first level array of the D3 selector.  Using the jQuery selector, the nodes are iterated over in “each” and the “data()” of the jQuery element is set to the “__data__” property of the D3 element.

Exchanging jQuery Data With D3

Now, let’s exchange jQuery data with D3 using a similar technique to the previous example:

//jQuery
var $nodes = $(".test-node")
    .append("span")
    .data("datum", {key: "hello", value: "world"});
 
console.log($nodes);
console.log($.cache);
 
//D3
var nodes = d3.selectAll($nodes.toArray())
    .datum({})
    .each(function(d){
        this.__data__ = $(this).data("datum");
    });
 
console.log(nodes);

Console LogIn the above example, the “.test-node” elements are selected using jQuery, the span child elements are appended and the “data()” method is used to store the “datum” {key: “hello”, value: “world”}.  Next, the D3 selector is populated using the “toArray()” method of the jQuery selector, the “datum()” method is used to initialize an empty data object and finally the nodes are iterated over and the __data__ property is populated with the jQuery data “datum”.

Conclusion

Both frameworks are very powerful and can live together in peace.  Information can be exchanged freely between the the two frameworks utilizing these or similar techniques.