My May #1GAM’s Progress

I’ve been trying to use my participation in One Game a Month to take each game project and try to learn one new aspect of game development in its development.

One thing I’ve never done is make a platformer. I figured that it would take some time to figure out the jumping physics and timings and collision detection with the ground versus a wall versus a floating platform, and I had no interest in pursuing it during a Ludum Dare compo.

That said, my project for May was meant to be an attempt at capturing the feel of a game I used to play a lot as a child. Frogs and Flies for the Atari 2600 used to keep my sister and me occupied for many an afternoon. Looking at Google Image Search, I can see that I’m not the only one who has ever wanted to make a game like it.

Oh, well. The important thing is that this is an opportunity to limit the scope of the game while I try to code up some jumping physics. The ground is static. There are no platforms to leap onto.

Unfortunately, due to day job crunch and various other responsibilities, I’ve only been able to dedicate a few hours to this project all month.

You can see the current status in this May #1GAM demo video, as it would be more interesting to see a box jumping around than a still screen:

I had some trouble with the jumping being inconsistent. Since I was using fixed-time steps, it made no sense to me why one jump would reach a different height than another.

Then I found that I wasn’t handling the jump states very well.

Jumping has three states: NOT_JUMPING, JUMPING, and FALLING.

In my code, if you hit and hold the spacebar, the state would be JUMPING and you could control how high you jump by how long you hold the key down.I f you let go of the spacebar, the state would change to FALLING. Once you hit the ground, the state changed to NOT_JUMPING.

For some reason, holding the spacebar down for the entire jump resulted in inconsistent heights reached. Imagine playing Super Mario Bros and getting frustrated that taking the same action results in randomly not being able to jump high enough to get to the next platform. What gives?

The video shows a white and gray box on the left side to indicate the max jump height and the last jump height respectively as I tried to figure out if it was a real or merely perceived problem.

I realized what the problem was eventually. Gravity was always being applied to the vertical velocity of the frog, even when it was on the ground. So in one update, the frog’s position hasn’t changed, but it’s velocity has. The next update, the position would change due to the velocity, and so when it fell below the ground, I’d reset the velocity and the position.

So while the player wouldn’t see any change in position, as it is a static box, there’s a 50% chance that the spacebar would be pressed while the player’s velocity is lower than 0, and the velocity of a jump was added to the player’s velocity instead of being assigned to it, which would have masked the issue (or solved it in the first place, if you prefer).

I changed the code so that gravity is only applied if the player is not in the NOT_JUMPING state, and everything worked much more consistently.

Then I added a direction and provided horizontal impulse as well, so each jump not only moves the frog up but also left or right. I want the player to use small jumps to move about, and bigger jumps to try to catch flies, similar to the advanced mode on the Atari 2600 game.

I’m pleased with how the jumping feels, although I find it awkward to figure out how to manipulate the relevant variables to get the jump how I want it. Gravity, initial jump impulse, additional jump impulse if you continue holding the spacebar during a jump, and time all conspire to say how fast and how high you jump, and I’ve been under time constraints to do the probably simple parabolic math that I’m sure it involves.

Like my past few months, I’ll probably have to limit the scope of this project significantly if I want to get it completed before the end of the month. I still need to add flies and way to catch them. I probably won’t have time to implement falling off the lily pad or day/night cycles. Even though I have a week left, it’s a rough week.

How’s your #1GAM project going?

My May #1GAM’s Progress is a post from: GBGames - Thoughts on Indie Game Development

Posted in game design, Game Development, Linux Game Development | Comments Off

14-f-cali: ragewang: uncomfortableconfusion: The cutest…





















14-f-cali:

ragewang:

uncomfortableconfusion:

The cutest kitten gifs ever on tumblr

do not do this to my frail and mortal being

Tomorrow im starting a cat blog thatll be my fourth tumblr but ok

Comments Off

Photo



Comments Off

Galcon 2 – beta11 – Ultracon & bricks & more!

Ahoy there, beta11 is ready for backers to download! Get it for Windows, Mac, or Linux. TestFlight users will get an email shortly with the latest build.

This build includes a ton of bug fixes for your favorite bugs, as well as the Ultracon mod by medeman and a Bricks mod by me. I’m getting close to being able to put together a rough edition of the Galaxy Map / MMO portions of Galcon 2, and the Bricks mod was a way for me to test out the basic code I need to add more interactive “menus” / “mini-games” to Galcon 2.

We were able to sent out some of the magnet sets this week! We’ve already gotten some pictures back in! International orders will take longer, and higher tiers are being shipped a bit later so we can combine on shipping. Here’s Kyle’s fridge:

If you want to test the game out with me, I’ll be on the g2s1 server for an hour or so :)

Thanks!
-Phil

Posted in galcon2 | Tagged | Comments Off

Photo









Comments Off

Hamumu Changes!

Hey folks! Look, I'm a-bloggin! I just made some kinda subtle, kinda major, changes to the Hamumu site just now.

I've removed the Mac versions of Loonyland, Kid Mystic, and Pumpkin Pop, since few people even own the Macs that could run them anymore (yay Apple for changing their OS constantly and having no backwards compatibility! I shall not rant). As much as I'd like to just leave them there for the few who could use them, it's far more often that they cause angry customers and refunds than happy results. I left up the two freebies (Retrovirus and Ninja Academy) that have Mac versions, just in case anybody wants to nab those still for whatever reason.

I've also removed the ability to purchase with anything other than Paypal or Yerfbucks! Well, I mean you can use a credit card to pay through Paypal, so it's not like you need a Paypal account to order. You can still use all the same methods you could before (no mail order, but if you send me a check, I'm happy to send you a game. Last time somebody did that was like 5 years ago! Trivia fact: Nobody ever used the fax order option, not once in over 10 years).

Now why did I do such a thing? Because just yesterday I set the wheels in motion to form a corporation! That's right, Hamumu is going to be an Inc. pretty soon. That doesn't actually mean anything for anybody on the outside, it's just something I'm doing for tax and liability purposes, but it's sort of exciting for some reason. I'm gonna get a share of stock! Anyway, the big issue is that transferring over the merchant account from the company to the corporation would've been complicated, and I have had my own complications with the merchant account in the past year, so I'm happier to dispose of it and just let things be easy instead of super-complex!

With my focus 100% on Growtopia (and rightly so indeed), I like to get all my ducks into a row that is very simple and organized in all other areas.

Speaking of Growtopia, I won't spoil anything, but we have BIG BIG BIG weekends coming up this weekend and next. Probably the biggest, most exciting, non-holidays we've ever done. Fun stuff is coming. We also broke 3,000 players online at once (without any lag problems!) for the first time ever this weekend, so we're still growing! Some other interesting stats that Seth was sharing with me yesterday: As I tweeted, the top time-played in Growtopia is somebody with 1270 hours played, and not a single dime spent, a statistic I'm very proud of. That tells me our game isn't "evil" with its in-app purchases. Also yesterday, the total playtime for the day between all players combined was over 48,000 hours - Five and a half years of human potential was squandered on Growtopia in a single day. Imagine what the world could've accomplished.
Posted in Uncategorized | Comments Off

SquirrelyJS – Squirrel Programming Language in the browser

Phew! Okay, my little science experiment from today (i.e. why I needed a makefile): SquirrelyJS.

Shot01

SquirrelyJS is a Squirrel Programming Language compiler and VM running in the browser. So it’s a bunch of JavaScript code, a bunch of C/C++ code compiled using Emscripten, all wired up to a shitty web page.

It’s barebones at the moment. You can edit/change/replace the code in the left side, and hit the Compile buttons to recompile it. Then click the Run buttons to run it, outputting to the left side.

The only commands that have any control are “print” and “error”. Both print text. print is black, and error is red.

print( "Hello World" );

error( "DANGER! DANGER! WORLD SAID HELLO BACK!" );

For more Squirrely programming ideas (and an explanation of the test program) go here:

http://www.toonormal.com/2013/05/06/squirrely-things-about-squirrel/

Ultimately, the reason I made this was to do some benchmarking, but I’m too tired today to do anymore (I nearly didn’t even blog about it once finished).

So ya, Squirrels.

Posted in Technobabble | Comments Off

Barebones Useful Generic Makefile

This seems to happen a lot for me. I’m testing/playing around with some code thing, and I set up some cheeseball compiling in a shell script. Then I get to a point and it’s just not enough, the compiling is taking too long, or so one. My major projects often have a nice makefile setup going, but my experiments, not so much. That’s because writing a makefile, despite being the same thing again and again for me, is tricky to get right.

So here’s a generic makefile I’d typically use. I’m posting it here so I can steal it as needed, but feel free to use it and hack away at it; That’s what makefiles are for. :)

This makefile is designed for simple GCC/G++ usage. It’s designed to put temporary/object files in an “obj/” folder, and the final binary in the “output/” folder. Also the generated file can be executed from the make command (via ‘make run’). If you have a specific set of command line arguments you want to pass to the program, specify them in the ARGS variable.

Lines that are too long should end with a “\” character, which continues on to the next line. Make sure there are no spaces after the “\”!!!

I’ve also included an optional common tweak I often do. Un-comment the SRC_PREFIX line to assume all code files and paths specified are in a “src/” folder.

# - ------------------------------------------------------------------------ - #
# Generic Makefile v0.1 by Mike Kasprzak (http://toonormal.com)
# usage: make | make info | make clean | make run
# - ------------------------------------------------------------------------ - #
TARGET_FILE     :=  MyGame.exe
ARGS            :=  
# - ------------------------------------------------------------------------ - #

# - ------------------------------------------------------------------------ - #
# Symbols (macros) to define ### e.g. USES_SOMETHING SOME_TEXT="Hello"
DEFINES         :=
# - ------------------------------------------------------------------------ - #

# - ------------------------------------------------------------------------ - #
# Path to individual source files ### e.g. Engine/Main.cpp Game/Player.c
SRC_FILES       :=
# - ------------------------------------------------------------------------ - #
# Folders to search for source files ### e.g. zlib zlib/extras squirrel
SRC_FOLDERS     :=  
# - ------------------------------------------------------------------------ - #
# Enable to assume all files are found in a "src/" subfolder (src/myfile.c)
#SRC_PREFIX     :=  src/
# - ------------------------------------------------------------------------ - #

# - ------------------------------------------------------------------------ - #
# Base directories to search for include files ### e.g. zlib squirrel/include
INCLUDE_DIRS    :=  
# - ------------------------------------------------------------------------ - #
# Base directories to search for library files ### e.g. /usr/local/lib mylibs
LIBRARY_DIRS    :=  
# - ------------------------------------------------------------------------ - #
# Library Files to include, with -l ### e.g. -liberty -lsdl_mixer
LIBRARY_FILES   :=  
# - ------------------------------------------------------------------------ - #

# - ------------------------------------------------------------------------ - #
# Compiler Flags ### e.g. --std=gnu++0x -fno-rtti -fno-strict-aliasing
FLAGS           :=
C_FLAGS         :=  $(FLAGS)
CPP_FLAGS       :=  $(FLAGS)
# - ------------------------------------------------------------------------ - #
# Linker Flags ### e.g. -static-libgcc -static-libstdc++ -static -mwindows
LD_FLAGS        :=
# - ------------------------------------------------------------------------ - #

# - ------------------------------------------------------------------------ - #
SRC_FILE_TYPES  :=  .c .cpp
# - ------------------------------------------------------------------------ - #
ALL_SRC_FILES   :=  $(wildcard $(addprefix $(SRC_PREFIX),$(addsuffix /*,$(SRC_FOLDERS))))
SRC_FILES       :=  $(addprefix $(SRC_PREFIX),$(SRC_FILES)) \
                    $(filter $(addprefix %,$(SRC_FILE_TYPES)),$(ALL_SRC_FILES))
# - ------------------------------------------------------------------------ - #
DEFINES         :=  $(addprefix -D,$(DEFINES))
INCLUDE_DIRS    :=  $(addprefix -I$(SRC_PREFIX),$(INCLUDE_DIRS))
LIBRARY_DIRS    :=  $(addprefix -L,$(LIBRARY_DIRS))
# - ------------------------------------------------------------------------ - #
# Where out files will output #
OUTPUT_DIR      :=  output/
OBJ_DIR         :=  obj/
# - ------------------------------------------------------------------------ - #
TARGET          :=  $(OUTPUT_DIR)$(TARGET_FILE)
# - ------------------------------------------------------------------------ - #
O_FILES         :=  $(addprefix $(OBJ_DIR),$(addsuffix .o,$(SRC_FILES)))
# - ------------------------------------------------------------------------ - #
O_DIRS          :=  $(sort $(dir $(O_FILES)))
# - ------------------------------------------------------------------------ - #
# Commands for Compiling C code, C++ code, and Linking #
CC              :=  gcc
CXX             :=  g++
LD              :=  $(CXX)
# NOTE: Using the C++ compiler for linking instead of ld because it's simpler. #
# - ------------------------------------------------------------------------ - #
RUN             :=  ./$(TARGET) $(ARGS)
# - ------------------------------------------------------------------------ - #


# - ------------------------------------------------------------------------ - #
# Link Command #
# - ------------------------------------------------------------------------ - #
$(TARGET): _makedirs $(O_FILES)
    $(LD) $(LD_FLAGS) $(LIBRARY_DIRS) $(O_FILES) $(LIBRARY_FILES) -o $@
# - ------------------------------------------------------------------------ - #

# - ------------------------------------------------------------------------ - #
# Compile Commands #
# - ------------------------------------------------------------------------ - #
$(OBJ_DIR)%.c.o: %.c
    $(CC) -c $(DEFINES) $(INCLUDE_DIRS) $(C_FLAGS) $< -o $@
# - ------------------------------------------------------------------------ - #
$(OBJ_DIR)%.cpp.o: %.cpp
    $(CXX) -c $(DEFINES) $(INCLUDE_DIRS) $(CPP_FLAGS) $< -o $@
# - ------------------------------------------------------------------------ - #


# - ------------------------------------------------------------------------ - #
_makedirs:
    mkdir -p $(O_DIRS) $(OUTPUT_DIR)
# - ------------------------------------------------------------------------ - #
clean:
    rm -fr $(OBJ_DIR) $(OUTPUT_DIR)
# - ------------------------------------------------------------------------ - #
run:
    $(RUN)
# - ------------------------------------------------------------------------ - #
info:
    @echo TARGET_FILE: $(TARGET_FILE) [$(TARGET)]
    @echo
    @echo SRC_FILES: $(SRC_FILES)
    @echo
    @echo O_FILES: $(O_FILES)
    @echo
    @echo O_DIRS: $(O_DIRS)
# - ------------------------------------------------------------------------ - #
.PHONY: _makedirs clean run info
# - ------------------------------------------------------------------------ - #

Posted in Technobabble | Comments Off

seaofdirac: My Abstract Algebra Professor played this for us in…



seaofdirac:

My Abstract Algebra Professor played this for us in class, warning, you won’t get it unless you’re a crazy math geek like me :3

Comments Off

typette: whisker-diaries: erikjohnsonillustrator: “The Ride”…





















typette:

whisker-diaries:

erikjohnsonillustrator:

“The Ride” by Rodolphe Guenoden

OH MY GAWD THIS IS AMAZING!! 8D

ah this guy is a classic artist :D I’velearned a lot from him

Comments Off

Doctor Who Cares? – A spinoff in which all is right with the…

















Doctor Who Cares? - A spinoff in which all is right with the ladies’ storylines and they take custody of the TARDIS every weekend to explore the universe together

Ladies night in the Tardis

Comments Off

State of the Investigation

So I’ve done a few scatterbrained posts lately that talk about things. Most of them had rather open ended conclusions, that were followed by wildly out-of-left field follow up posts. Here’s me making sense of that.

Evaluating Middlewares: Unity does good 3D, bad at JS

Unity’s “JavaScript” isn’t JavaScript, it’s better named UnityScript. UnityScript is kinda terrible, essentially being just a different syntaxed less featured C#. But var is allowed, so uhhh… *shrug*.

I still don’t care much for C#, but I think Unity’s 3D workflow is excellent. Fantastic even. I have 3D projects I want to do, and when the time comes, I’ve convinced myself I should do them in Unity.

That’s 3D only though.

Haxe NME is cool, impressive and all, but it seems more a home for Adobe Flash refuges right now. Adobe, I know not what they’re thinking. I’m very confused by what they’re up to anymore, so I’m glad the Flash community has a way out. That said, I’m not particularly attached to the stricter typed Ecmascript language used by Flash/Haxe/Loom. I like JavaScript. I think JavaScript is great. So I don’t entirely feel right with Haxe NME. Highly recommended for Flash devs and people not me. ;)

JavaScript is cool

JavaScript *is* cool. I’ve been working with it more and more lately. I made a game with Derek Laufman of Halfbot using JavaScript for Ludum Dare 26.

Toom09

Time was short during Ludum Dare, but we came up with some neat ideas, so we’re redoing the game. A “Director’s Cut” if you will. It’s still taking place in the one room, but we’re planning to make both the room and the interactions you have inside it way more interesting.

JavaScript is cool, but I’m hitting a limit of HTML5 Canvas 2D now in the latest builds of TOOM. Chrome is fine, but Firefox has seen a significant framedrop after adding a few more Alpha operations. I will be reintroducing frame skipping in to the code, but this doesn’t bode well for the near term “best user experience” of TOOM in the broswer.

That said, I fully intend to finish the TOOM Director’s Cut as an HTML5+JavaScript game. It just may be, before its time, when it comes to Canvas 2D performance. Working in JavaScript has been great, and inspired some really great alternative-to-Unity workflow ideas. I’ll come back to this. First though, what I think of App Packagers for Desktop HTML5 apps.

Packaged HTML5 Apps (Tool): Abandoned

In January 2012, I ported the unreleased Beneath Darkness prototype to some HTML5 packager. The company behind the packager was running a contest, and my intention was to enter the game in that contest. I wasn’t able to finish enough in time though, so I never submitted. That was fine though, as the winning games were definitely better and more complete.

The thing is, I can’t remember what that packager or the company was called.

It doesn’t really matter though. Like the Chrome Store, apps built for this packager were only for their proprietary HTML5 app store. I seem to remember a blue acorn, which may have been their logo. What disappoints me is that packager ran the game perfect. No issues with sound, no issues disabling linear filtering on image scaling, no issues loading files. Yet today, running the same prototype in both AppJS and Node-Webkit fails to load the map file. I’d be fine if Node-Webkit had no issues loading TOOM using PreloadJS, but it does. I might have been able to get NOOK working in Node-Webkit without any changes, but long story short I’m not happy.

Google’s Chrome App Packager stuff sounds like they solve the key issue (XMLHTTPRequest’s locally are okay), but it’s proprietary, and again only available to apps intended for distribution in the Chrome Store.

Even if it’s something that would be best fixed inside PreloadJS itself (support file://), that’s fine, but that’s not working 100% right now. I still have to do all my testing via a mini webserver running locally. My intent was to build a generic editor for a TOOM related project using HTML5, but I’ve decided against it. Building a Tool in HTML5 only saves me time if it works… right now… today.

I’m very unhappy with the state of packaging HTML5 apps as Desktop Apps.

Renstalled Empscripten, Embracing WebGL

NOOK, BEARly SEASONed, and the unreleased Last Gun prototype were made using Emscripten (C++ and JS). TOOM and the unreleased Beneath Darkness prototype were written in pure JavaScript.

I’m glad I went back to pure JavaScript for TOOM though, because HOLY HELL I learned how REALLY GREAT some of the features of JavaScript are. You know JSON right? Well it’s even better in JavaScript. :)

http://www.toonormal.com/nice-efficiency-things-about-javascript/

But like the headline says, I’ve since reinstalled Emscripten. My post from earlier today details this process, which was notably different than from when I did it 1 year ago. Better… except for the build time (70 minutes to build LLVM+Clang… and I had to do it twice).

http://www.toonormal.com/emscripten-2-the-emscripting/

And like the above article mentions, there’s now the AsmJS spec, which is an effort that makes JavaScript code run at only half the speed of native, versus the 6x slower than native I was promised last year.

I’ve been sort-of against WebGL, ironically, being an OpenGL guy. Against is a harsh word. More like, ignoring it. After all, Microsoft will never add it to Internet Explorer… or will they? Yes if the leaked Windows Blue version of Internet Explorer is to be believed, WebGL support is there now, so therefor coming soon.

Good.

What WebGL also brings is some potential Canvas graphics performance improvements. Your render code will have to be ported over to WebGL (OpenGL ES2), but with a little bit of batching, things get nice and quick.

https://www.scirra.com/boosting-mobile-html5-game-performance-with-webgl

Oh and Unreal Engine 3 now runs in the browser, thanks to WebGL and Emscripten.

So alright. If Unreal Engine 3 can do it, surely a WebGL accelerated 2D engine can.

Now for the final piece.

Squirrel! Like JavaScript but Nuttier!

Between work on the TOOM Director’s Cut… actually the other way around, I’ve returned to my Squirrel research in a big way. As far as languages go, Squirrel is very much like JavaScript, but with everything on my JavaScript wishlist already implemented and working great (operator overloading, separate integer and float number types, 32bit, delegates woo woo, etc). Here’s some exploration:

http://www.toonormal.com/2013/05/06/squirrely-things-about-squirrel/

My only beef with the language is that I’m comfortable with using var in JavaScript, instead of local like Squirrel uses. That said, they’re not the same, and even var in JavaScript is actually a problem: Such a big problem, that the EcmaScript 6 spec is introducing a new keyword let which works how you’d expect var to work.

Anyways, my mini-project of the day was to get Squirrel building in the browser (using Emscripten), and to build a very basic HTML interface for invoking the compiler and seeing the results. I’m betting that, since Unreal Engine 3 can run in the browser, it’s not unreasonable of me to expect instant execution of small Squirrel scripts. If that’s the case, then if paired WebGL, it may be reasonable to expect 30-60fps performance of a C++ game driven by Squirrel scripts. I’m not exactly interested in developing web games in Squirrel, but I’m investigating whether if I commit to Squirrel as a native game logic language, I can still generate playable web versions of games.

Long story short, I want the advantages I discovered in building TOOM in JavaScript in my Native Game Deving, and I already have proof that they do work.

Regrettably, I haven’t yet finished this Squirrel building project yet. Getting Emscripten working again ate up most of my afternoon (long Clang compiles). Then there was the power outage, and this blog post, so I think I’ve done enough for today.

I may try just compiling Squirrel with Emscripten, then I’m calling it a night.

EDIT: Yep. So far working just fine with NodeJS.

#!/bin/bash

emcc -O2 \
	-I include/ \
	squirrel/sqapi.cpp \
	squirrel/sqbaselib.cpp \
	squirrel/sqfuncstate.cpp \
	squirrel/sqdebug.cpp \
	squirrel/sqlexer.cpp \
	squirrel/sqobject.cpp \
	squirrel/sqcompiler.cpp \
	squirrel/sqstate.cpp \
	squirrel/sqtable.cpp \
	squirrel/sqmem.cpp \
	squirrel/sqvm.cpp \
	squirrel/sqclass.cpp \
	sqstdlib/sqstdblob.cpp \
	sqstdlib/sqstdio.cpp \
	sqstdlib/sqstdstream.cpp \
	sqstdlib/sqstdmath.cpp \
	sqstdlib/sqstdsystem.cpp \
	sqstdlib/sqstdstring.cpp \
	sqstdlib/sqstdaux.cpp \
	sqstdlib/sqstdrex.cpp \
	sq/sq.c \
	-o bin/sq.js

// Usage: node sq.js [args]
// FYI: Emscripten compiled things can only access files inside their virtual file
//      system, so passing a .nut file on the command line will only work if you
//      added it during build. i.e. --embed-file myfile.blah
//      NOTE: --preload-file wont work in the above example, because node.js lacks
//            a window object and XMLHTTPRequests. Must be --embed-file.

C++11 Support Feature Complete in Clang and GCC soon!

Now this is some awesome news. Clang 3.3 and GCC 4.8.1 are expected to be fully compliant with C++11 in their upcoming next versions.

GCChttp://gcc.gnu.org/projects/cxx0x.html
Clanghttp://clang.llvm.org/cxx_status.html

There’s still the problem of compiler vendors being slow to upgrade their GCC and Clang versions to newer ones, but this milestone should be a good kick-start.

Something also rather neat, Clang is adding C++1y (C++14?) features already. One that caught my eye, BINARY LITERALS! So just like you do 0×10 for the hexadecimal number 16, you’ll be able to do 0b11010011 to write binary. :D

I have a header file, named Binary.h, that’s literally filled with every 8-bit combination of b0 to b11111111. Looks like I’ll be able to retire it some day. :)

End of Report

This post grew rather large ‘eh? Alright then, I’m done.

Posted in Opinion, Technobabble | Comments Off

Galcon 2 – beta10 – Game UI overhaul

Ahoy there, another build is ready for backers on Windows, Mac, Linux. TestFlight folks will get emails shortly with a new build too!

Particularly cool additions are left-handed mode, and real portrait orientation support! Some options like “color-blind mode” and “multi-touch mode” are listed in the Controls, but they aren’t implemented yet. Please check out the Settings / Controls and try out settings and find your favorite!

Funny dev bug:

This build largely fixes a ton of iOS related issues and overhauls the in-game user interface. I tried to fix most of the issues reported! Please give it a whirl, I’ll be online for a bit on the server if anyone wants to hang out! Please post on the forums if you have any comments.

Also, the magnet sets are all pretty much packaged and shipping will begin to all the $25 backers next week! I’m holding off on higher tiers because we’re going to try and combine shipping with the box sets. Thanks for your patience!

Cheers!
-Phil

Posted in galcon2 | Comments Off

Emscripten 2: The Emscripting (or setting it up again, a year later)

So last year, Derek and I created a little game called Nook. Nook was an interesting game that was half JavaScript and half C++, running in the browser (as 100% JavaScript). Things were still new with Emscripten. At the time it had only recently reached the point where it could work with standard C++ libraries without issue. Performance claims were about 6x slower than native. Everything worked out great, so I did little writeup on it:

http://www.toonormal.com/nook-and-emscripten-a-technical-look/

There were some talks at GDC this year on Empscripten, and regrettably I missed those. And just last week Unreal Engine 3 was ported to the browser using Emscripten. Thanks to recent optimization work, and the new AsmJS spec, its seems Emscripten code is close to 2x slower than Native in AsmJS optimized browsers. And as always, a great place to hear about interesting new things with Emscripten is on the lead developers blog and twitter.

http://mozakai.blogspot.ca/ | @kripken


Now formalities are out of the way, I’ve given myself a new project: Squirrel VM in the browser.

This blog post wont cover “SquirrelyJS” (a nickname I just came up with for the project), but setting up Emscripten again.

Setting Up Emscripten

I’ve just recently installed a new hard drive in my laptop, so I need to reinstall Emscripten. I’ll be following the tutorial here:

https://github.com/kripken/emscripten/wiki/Tutorial

Starting with the downloads, I had to install GIT (I’m an SVN guy). I like TortoiseGIT, because I also like TortoiseSVN (and TortoiseHG). TortoiseGIT requires MSysGIT to work.

It’s worth knowing that the Emiscripten you get out of GIT is the full thing usable as-is. No compiling is required. Once everything is installed correctly (Clang, Python), and your paths are set up correctly, it will work.

Python 2.7 I already had installed in C:\Python27. Emscrpten tries to be clever and use a file python2.exe, which doesn’t exist by default. This can be fixed later, but you can create a symlink, or make a copy of python.exe as python2.exe in the python directory. It’s 27k, so an extra copy of python.exe wont hurt.

NOTE: Java is required to use the closure compiler (i.e. JavaScript optimizer). For some reason this isn’t mentioned in the setup instructions.

Building LLVM+Clang

I use MinGW with MSys, and while yes there is an “experimental” download on the Clang/LLVM page, I wasn’t able to get it working. So instead, I had to build it from source.

WARNING: DO NOT BUILD FROM SVN! EMSCRIPTEN IS ONLY COMPATIBLE WITH THE CURRENT STABLE RELEASE! (Also skip the test-suite)

I followed the instructions here, with one change:

http://clang.llvm.org/get_started.html

EDIT: USE AS REFERENCE ONLY! You should only ever use the stable sources. Uncompress clang in to the tools folder as suggested (renaming clang-3.2.src to just clang), and optionally in projects compiler-rt (renaming compiler-rt-3.2.src to just compiler-rt). Skip the test-suite.

My change I did “../llvm/configure --enable-optimized --disable-assertions“, since I wanted a nice fast release build of LLVM+Clang, not a slower debug build with Asserts.

I also had to disable my current install of Clang, as it was trying to use Clang to build Clang+LLVM, which was broken. Only a problem if you tried to use the experimental package they provided.

An unfortunate downside, I was unable to use “make -j 4“, which uses multiple cores to compile. This is the 2nd time in the years I’ve been using MinGW+Msys I’ve come across something that make’s -j hasn’t worked (I can’t remember what the other one was, but it was a few weeks ago). It deadlocked on compiling the 4th file, which is not a good way to finish building anything. ;)

Compiling in a single thread took me over an hour. :(

Once built, “make install” to put it in my /usr/local/bin.

Configuring your system for Emscripten

First things first, we’re going to need to set some environment variables. You can do that here:

Control Panel->System->Advanced System Settings->Environment Variables

The Path is often the most important variable to tweak. Add new paths separated by semicolons (;). I added:

;C:\Python27\;C:\Emscripten\

There are some optional environment variables you can add here too.

EMSCRIPTEN – Where emscripten is (e.g. “C:\Emscripten\”).
LLVM – Where Clang+LLVM is. (e.g. “c:\MinGW\\msys\\1.0\\local\\bin”).
PYTHON – Python executable. (i.e. “C:\Python27\python.exe”).

Browse to the Emscripten directory with MSys, and run the following.

python emcc

Because its the first run, this will create an Emscripten configuration file in your home folder. Mine was here:

C:\MinGW\msys\1.0\home\Mike\.emscripten

In this file you can edit/set the location of Python, Clang/LLVM, etc. You can also change it from using python2.exe to python.exe if you want.

IMPORTANT: You need to set your temp directory. I modified the TEMP_DIR line as follows:

TEMP_DIR = os.path.expanduser(os.getenv('TMP') or '/tmp')

After all, the rest of the lines in the file use this os.getenv function, so why not temp too?

Okay! That should be it.

Now if everything is set up correctly, you should be able to run clang and have it not crash.

clang /c/Emscripten/tests/hello_world.cpp
./a.out

You should also be able to run emcc without explicitly invoking python now.

emcc /c/Emscripten/tests/hello_world.cpp
node a.out.js

Node is NodeJS, the tool for running JS files on the command line (without an .html page).

Posted in Technobabble | Comments Off

Structs and references (again)

Structs, or value classes, have been a problem since I decided I wanted them. Their only raison d’être has been performance, as functionally they can be entirely replaced by objects. And additionally, the value type semantics is inherent to some of the built-in classes (number, boolean, text, etc.), so it’s a feature that we’ll need at low level no matter what. Might as well make it available to the user.

Reminder: the struct problem

Structs were originally defined semantically as “exactly like objects, but always copied at assignment”. And implementation wise, allocated on the stack (or even registers if the compiler sees it fit).

This comes with two major problems:

  1. The self parameter for methods defined on structs would be itself a copy of the original, therefore making every struct immutable.
  2. Even assuming the first problem solved, member access is a method call, and therefore in case of struct members, would return copies, making struct members immutable.

After several rounds of self discussion, I had come up with the solution that the self parameter would be actually a reference, and that some methods (in particular member accessors) would also return references, which could be returned immediately as references as well. Every other use would be a copy.

This solution was utterly unsatisfying, because of all the hidden shenanigans used to make “expected behavior” work:

obj.structMember.foo = 5
someStruct.modify()

What would Jesus do?

When in doubt, steal. Both C++ and D have structs and methods on structs. Assembly analysis reveals that they (obviously) pass the this parameter as a pointer, and access it as a pointer (this-> in C++, and this. in D).

However, since both languages also have pointer and reference syntaxes, any other plain struct argument or return value will be copied unless stated otherwise.

Go and Rust, however, have an interesting twist on this: methods are defined not in classes, but for specific receivers. In other words, the self or this parameter is explicit. And it can be of either type: the plain struct, or a pointer to it.

The method syntax there is a very thin wrapper over the low level reality, which is that methods are functions. And if you can decide to pass parameters by copy or reference to a function, why not also the not-so-special self?

If you define a method on a plain struct, then it will be copied, or equivalently, read only. If you define a method on a reference to a struct, then obviously, the struct can be modified in place.

And in a funny manner, it works also for primitive value types. With our extension syntax, we could very well have (assuming passing by reference):

extend num
    method doubleIt()
        self = self * 2
    end
end

-- somewhere
local a = 5.0
a.doubleIt
assert(a == 10.0)

In any case, it seems that self must be passed by reference, always. This was already our earlier conclusion. What about problem 2?

Return by reference

The second problem is linked to the fact that sool has member access done through methods and therefore returning a member (or an array element, too) would return a copy, making it impossible to modify without reassigning a whole new struct.

In C and others, member access through the dot is really, in low level, returning a reference (the address of the field inside the struct), which is then used to read or write info.

What if sool always returned structs by reference?

-- obj.struct is "a reference"

obj.struct.doThing      -- or obj.struct.foo = 1
local copy = obj.struct
return obj.struct

Look at the three things we did there:

  1. calling a method on the returned struct
  2. assigning the struct to a local (or something else)
  3. returning the struct

The first one would, as expected, call the method on the remote struct, by forwarding directly the reference we just received from obj.

The second one would copy the struct, because the reference is not a type (like a pointer), you can’t store it or modify. It’s always automatically dereferenced.

The third one would return the reference directly, as expected for chaining accesses.

So far so good.

What happens with:

method Struct giveStruct()
    local foo = Struct()
    return foo
end

We’re supposed to return foo by reference, but it’s a local, it’s living on the stack, its life ends when the method returns. It’s a classic error in C.

Rust allows it, in the form of the “borrowed pointer” a general purpose pointer that can point at anything of the right type. Even locals from inner functions. How does it work? Simple, the local is boxed into a heap allocated memory chunk, and a reference to that is returned. Of course, garbage collection takes care of the details after use.

Wow, wait, isn’t that horrible performance? Allocating memory for a return value? Well, it can probably be optimized somehow. First if the method is inlined, the whole allocation step can be bypassed. Also, the calling method might reserve some stack space and have the callee fill it with the value. The compiler might be doing that anyway, when returning “normal” structs.

What matters is that the semantics at high level are respected. If you return a local struct, all that can happen to it is calling a method on it, in which case it works, or be copied somewhere else, which works as well.

Are there downsides to always return structs by reference? It can be a tad confusing that value objects are always copied at assignment, except the “special assignment” that is returning a value. Then again:

local foo = obj.member

obj.member is the return value, it’s a hidden temporary local variable. We might argue that it hasn’t been assigned yet. Only the presence of the = sign could be considered as an “assignment” in the rule that struct are copied at assignment. That and when passed as arguments, because they get a new local name in the function.

Again, as long as the semantics are clearly defined, everything is allowed. But it’s still not very satisfying. It feels like an added hack, for something that should be a core feature.

Finding the culprit

The second problem was based on the fact that member access in sool is done through methods.

foo = obj.member    -- is really method: Type member()
obj.member = foo    -- is really method: member=(Type)

This is always fine with objects, because they are stored as references already. The problem arose with structs.

So why did we have this in the first place?

  1. So that member access and method call have the same apparent semantics (encapsulation, from the outside it doesn’t matter if it’s an actual member or if you computed the result, or set something elsewhere than in a member)
  2. So that member access participates in the class’s interface (for dynamic dispatch)

Earlier, we still had inheritance and the idea was that you could override a member with methods. Now we have interfaces and the idea is that an object with a member Foo foo works just the same as an object with a method Foo foo().

So I decided, members only define the memory layout of the object, but they are accessed with compiler provided methods, the getter and the setter. And you can also define methods that looks like getters and setters, and make the object look like it has another member.

First point: can be waved by just allowing it in the grammar. obj.foo can be either accessing member foo or calling method foo, whichever happens to exist.

Second point: the compiler can provide glue methods, used specifically when casting an object to a generic, to access its members as if they were methods. No fuss required.

And then define “member access” as this magical operation that brings the desired nested variable to first level, to be used as right or left value.

To be fair, documentations don’t always explain what member access is. D just tells you what the syntax for it. Lua has a fuzzy explanation about variables being location where values can be stored. Rust is quite formal though, about lvalues, rvalues, and what they mean in different contexts.

Anyway, the result is that these rules – explicit or not – involve the fact that an expression is used:

  1. as a value as rvalue
  2. as a location as lvalue

Even the most evident thing, assignment, is actually quite confusing when you think about it.

Even then…

Assume we define member and array access as the magical thing that always works, and is separate from method call. We still want the glue accessors, and the glue indexing so that we can build wrapper objects that look like containers (especially when embedding):

object Foo
    method Elem [](uint index)
        return Elem()   -- dummy
    end

    method []=(uint index, Elem e)
        -- discard
    end

    method Elem fakeMember()
        return Elem()   -- dummy
    end

    method fakeMember=(Elem e)
        -- discard
    end
end

-- later
local foo = Foo
foo[19].modify()
foo[50] = Elem()
foo.fakeMember.modify()
foo.fakeMember = Elem()

Looks cool. Except that for this particular Foo class, the syntaxes for field access and indexing will not be the magically defined low-level ones, but resolve as simple method calls.

In particular, the modify() calls would happen on the variables that were returned. If we don’t have a syntax to return a reference (ie. an address), we can’t extend the “expected behavior” to manually defined accesses and indexings.

Explicit references

So it’s clear, we need references. Maybe not as a full blown recursive type, but at least for the matter at hand: return values.

-- suppose foo is a member or in an array we know of

method ref Elem fake()
    return foo      -- return the address, not the value
end

-- elsewhere

local foo = obj.fake    -- dereference, copy
obj.fake.modify()       -- modify original!
obj.fake = haha         -- yep, we know where it is!

Huh, we don’t even need the setter methods anymore. Any method that returns a single reference can be used as if it was a member. Thus we can even come back to the original concept that member access is method call. A method call that returns a ref, and can be used both as left and right value!

Same goes for indexing. Same goes for anything. Would that be the magical solution? We needed the reference at least at low level anyway for the self param, so why not for return values.

Note that it’s necessary to have them for objects as well, now that the fake= style setters are gone. But when they’ll be used in rvalues, the compiler will happily bypass the whole “return a ref and deref it immediately” part.

We lose the ability to use foo= setters for doing anything else than actually setting a real variable, like doing input validation. Maybe it wasn’t a killer feature anyway.

Conclusion: it’s actually pretty simple

  • for value classes methods, the self hidden argument is passed by reference
  • any method with a single return value can be declared to return by reference
  • a reference (as returned by such method) cannot be stored, it must be either:
    • the recipient of a message
    • assigned to a variable, which copies the original variable
    • returned as a reference
    • used as left value in an assignment
  • each member Class name in a class has a compiler provided accessor method ref Class name() that returns a reference to it

And I think that’s it…

Fun stuff

  • obj.foo(1,2,3) = 4 is completely valid and simplifies the grammar. Every method call can be a left value, the validity is determined by semantic analysis (is it a reference?)
  • built-in read-only variables: make an accessor wrapper. Return normally, it’s a copy, return by reference, the caller can modify it (whether it’s a struct and all its content, or an object reference)
  • return by ref or not is now part of the method’s prototype, and participates to interfaces, for binary compatibility between methods in dynamic dispatch. Compiler could automatically wrap by-ref into normal, though.
  • the word “reference” is getting a tad confusing, given that it’s the one we use for these object pointers that are automatically dereferenced

A change of words

Since it can be confusing to have “reference” mean two different things (albeit related or even similar), maybe we can slightly hide this concept in a higher-level point of view. But still explicit, because we don’t want to hide things too much.

We now know that this new “return by reference” concept is essentially meant to wrap containers and provide accessors to internal (or in any way remote) variables. And that the most natural accessors are these that the compiler provides for the class members. Why not call this an “accessor method”, and make it even clearer:

object Wrapper
    Struct struct
    #Struct array

    accessor Struct fake()
        return struct
    end

    accessor Struct [](uint index)
        return array[index]
    end
end

They’re still methods, but they return a “magical thing” that makes the expression a left value, and makes you modify the original returned thing, not a copy.


Posted in sool | Comments Off

Evaluating JavaScript to Native-App Packagers

EDIT: For reference I’m leaving this post as-is (except for the new ending), but it seems AppJS is a lot more painful to use after all. Ugh.


Long story short, I need to write a tool with a UI. I want it to be portable, just in case. And because JavaScript is “fine”, I’m investigating what packaging options there are.

I’m not doing a very scientific test. All I’m doing is throwing TOOM, an adventure game Derek Laufman and I made for Ludum Dare 26 at it. If it works, I’m happy. If it fails, I’m not.

TOOM uses SoundJS and PreloadJS. PreloadJS wont work if the browser is reading from the local file system (i.e. file:///blah.html). So developing TOOM, I’ve had to use a tiny webserver running locally (currently Mongoose, was MiniWeb).

Chrome Packaged Apps

http://developer.chrome.com/apps/about_apps.html

Despite the name, despite the wording, this doesn’t create standalone apps. It creates content for distribution by Google’s Chrome App Store only.

It’s also not officially live yet. You can make apps, test them, but can’t Publish. Beh.

Node-Webkit

https://github.com/rogerwang/node-webkit

A good simple solution, based on NodeJS and Chromium, regularly updated (Intel Sponsored), but fails the TOOM test. It starts loading, but dies at an unusual place (complaining about one of my source files missing… which is definitely there if it can start loading at all).

Adds about 54 MB to the total size (~23 MB zipped).

AppJS

http://appjs.org/

A fantastic solution, also based on NodeJS and Chromium, and so far the only thing to pass the TOOM test (no audio and slower, so clearly using an older version of Chromium). The very very saddening part however is that there’s only 1 guy on the project, and he’s too busy.

Also adds about 54 MB to the total size (~22 MB zipped).

Visual Studio 2012

http://www.microsoft.com/visualstudio/eng#downloads

Untested, but this option is Windows only, and there may be other caveats. Any code written for DiskIO and file manipulation will only work on Windows. No WebGL support. That said, the JS code may compile down to CLI bytecodes (dot net), so performance might be better. Also how an app is structured may not mirror how a web project is created (index.html and all files). Untested though.

Adobe Air

http://www.adobe.com/devnet/air/air-sdk-download.html

Nope. Created my descriptor file, modified it to use the HTML file, then ran it with adl (adl D:\Toom\application.xml). After fixing the one bug it reported, it just sits there… waiting. Running I assume, but there’s no action.

NOTE: Instructions for running and packaging I found inside “AIR SDK Readme.txt” in AirSDK.

TideSDK

http://www.tidesdk.org/

Formerly known as Appcelerator Titanium for Desktop.

Finally, another one that passes the TOOM test. TideSDK is based on Webkit, but a seemingly an older version of webkit. CSS Fonts did not work, the framerate was even slower than AppJS, and no audio. Still, it was interesting. Downside is they seem to be short on funds too; Their blog reminds me of PBS.

More choices, no good ones

http://stackoverflow.com/questions/11015811/html5-desktop-wrapper-framework

Conclusion

There’s no safe/good/active choice, but AppJS impressed me the most. As far as portability goes, I think what I want to be using is something that combines Chrome and NodeJS, but not Webkit. Plus it gives me a reason to learn NodeJS too. My Browser performance and debugging experience is just so much better with Chrome, even though I don’t use it as a primary browser (I use Firefox instead).

Regrettably AppJS right now today is a bit of a gamble, since it’s just one dude behind it, and he’s made it clear he doesn’t have the time. But it does exactly what I want, so *shrug*. There’s talk of a Kickstarter, and I hope this sees the light of day. Totally a worthwhile project.

PLOT TWIST!

Not a good one though.

Something I hadn’t really realized before was how AppJS is actually working. From what I can tell, it’s actually running a small web server, i.e. the NodeJS part. Your main JS script file is standalone and disconnected from what runs in the browser context… YET, you control maximizing/minimizing windows, the contents of menus, task bar appearance from the NodeJS side. Your app is standalaone, caged inside the browser context.

Now, there may be a way to pass data between the NodeJS side and Chromium side, similar to making web requests in general. It’s not documented though, so *sigh* not sure where to start.

Node-Webkit might actually be more of what I want, since it’s about introducing the Node features in to Webkit. That said, it failed the TOOM test.

Ah well, enough of this for now.


More (Unrelated) Notes

Appcelerator’s Titanium I missed when looking at HTML5 to Mobile options.

Free, or ~$12000 a year (haha):

http://www.appcelerator.com/platform/titanium-platform/

Jo is an interesting JS UI Kit I wasn’t aware of before.

http://joapp.com/

There’s a thing called Chromium Embedded:

stackoverflow.com/how-to-develop-desktop-apps-using-html-css-javascript

Posted in Technobabble | Comments Off

neoteotihuacan: A few months back, a small twitter hashtag got…



















neoteotihuacan:

A few months back, a small twitter hashtag got kind of crazy - #overlyhonestmethods

Its a hashtag full of scientists admitting shortcuts in research, along with the daily face palms and annoyances of a scientific lifestyle. Science is hard, yo. 

I decided to steal some of the more popular tweets from the trending hashtag along with some random images of scientists from Google image search and combine them. This is the result. it works, I think. 

The full album can be found here: http://imgur.com/a/x77kL

Comments Off

The Princess Who Saved Herself

femfreq:

Jonathan Coulton’s song about a princess who doesn’t need saving by anyone is soon to be turned into a comic book with Greg Pak via a stretch goal on this crowdfunding project.

image

Comments Off

Squirrely things about Squirrel

More notes. This article contains a longer more comprehensive list of differences, but I want a more concise list for both my own reference, and for when I’m teaching.

Squirrel 3 documentation.


Tables are Objects

In JavaScript and Squirrel, you have two types: Arrays which are indexed with an integer number, and Objects/Tables that are indexed with a string. In JavaScript the string one is called Objects, and in Squirrel one is called Tables. The name (and some of the original code) is borrowed from Lua.

Members of Arrays and Tables in Squirrel are called Slots.

The “this” member of function scope is called the Context or the Environment.

.length is .len()

MyArray <- [1,2,3];
MyTable <- {hello=true};

print( MyArray.len() + "\n" ); // 3 //
print( MyTable.len() + "\n" ); // 1 //

The meaning of “this” can be changed in a function call

Player <- { name="Steve" };

function MyFunc() {
    print( this );
}

MyFunc.call( Player ); // "this" will be Player //

Player.Func <- MyFunc;

Player.Func(); // Call as a member, "this" will be Player //

MyFunc(); // Otherwise, "this" is the root table when not called as a member.

The “in” operator (hasOwnProperty)

To check if a Table has a member, use “in”.

if ( "offset_x" in Player ) {
    // Player has a member offset_x //
}

function Blah() {
    if ( "offset_y" in this ) {
        // Whatever context this function uses has a member offset_y //
    }
}

Blah.call( Player ); // An example for calling with different contexts (i.e. the "this")

if ( "Player" in getroottable() ) {
    // There is a global variable called Player //
}

var and local are not the same

In JavaScript, you use the var keyword to declare a variable. Depending on the scope of that variable (in a function, in global scope), the variable is declared there.

In JavaScript, to add a member variable to class, you don’t use var but instead use dot syntax and directly set it. i.e. MyObject.MyNewMember = value;

In Squirrel, you have a keyword local, which is like var, but only applies to function level scope. In Squirrel, Global Scope is actually a table called the Root Table. To add a member to a Table, you use the arrow syntax.

MyGlobalVar <- {}; // Creates a global variable, i.e. adds to the root table
MyVar <- true; // Assign any type, not just arrays and tables.

function MyFunc() { // Synonym for "MyFunc <- function() {"
    local MyLocal = 12; // A local variable
    MyGlobalVar.NewMember <- 10; // Adds NewMember to the table and assigns it a value
    MyGlobalVar.NewMember = MyGlobalVar.NewMember + MyLocal; // Now that it exists, = works
    if ( ::MyVar == true ) { // Double colon syntax to explicitly access Global Scope
        print( MyVar ); // Double Colon syntax isn't required, but without it uses local first
    }
    return MyGlobalVar.NewMember;
}

That said, local is allowed in the Global Scope, but it doesn’t add objects to the root table. Instead, like all other locals, it adds them to the local scope (i.e. the stack).

//Scooter <- 10;      // Root Table (Globals) //
//const Scooter = 10; // Const Table (Global Constants) //
local Scooter = 10;   // Stack //

function Hello() {
	if ( "Scooter" in this ) {
		error( "is in this\n" ); // For now, this is the root table
	}

	if ( "Scooter" in getroottable() ) {
		error( "is on Root\n" );
	}

	if ( "Scooter" in getconsttable() ) {
		error( "is on Const\n" );
	}

	if ( "Scooter" in getstackinfos(1).locals ) {
		error( " is on Stack\n" );
	}
}
	
Hello();

// Output: is on Stack

A related topic is Free Variables.

FYI: getstackinfos() returns a Table, see the docs for more info. The locals member is a Table of all local variables. Also the argument to getstackinfos is the call stack level. 0=Current Function, 1=Caller, 2=Caller’s Caller, etc.

Closures

Closures are Functions. Both terms are used interchangeably.

The value of “this” can be changed using the “.call” method of a function. This is called the Environment Object.

An explicit Environment Object can also be bound to a function, forcing all calls to use that environment and ignore the typical value of “this”. This may seem strange, but this whole mechanism will be useful later.

Here’s a discussion on JavaScript closures that may be of interest: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures

// Assume Player has a delegate that sets its _tostring to return "Player"
function MooMoo() {
	error( "** " + this + " " + getroottable() + "\n" );
}

MooMoo(); // Default Env is Root Table //
MooMoo.call( Player ); // Specific Env: Player //

Moo <- MooMoo.bindenv( Player ); // Create a copy of MooMoo with Player always bound.

Moo(); // A replica with a specifically bound Environment //
Moo.call( ArtFiles2 ); // Overloading that environment (fails) //
MooMoo(); // Again just to confirm Original was unmodified //

// ** (table : 0x006B8730) (table : 0x006B8730)
// ** Player (table : 0x006B8730)
// ** Player (table : 0x006B8730)
// ** Player (table : 0x006B8730) // Unexpected result! bindenv permanent!
// ** (table : 0x006B8730) (table : 0x006B8730)

JSON Syntax Caveats

One of the main reasons I’m so insistent of Squirrel is because it’s extremely close syntactically with JavaScript. So far, I’ve found a way to do everything I like in JavaScript with Squirrel, but sometimes it’s just works a little differently.

As of Squirrel 3, you’ve been able to use a JSON-like syntax for building objects. Here is a snippet ported over from TOOM:

ArtFiles <- [
	{ "name":"Man", "value":"art/anim.png", "tile_w":128, "tile_h":128, "anchor_y":128 },
	
	{ "name":"BG1", "value":"art/toombg_bg_01.png" },
	{ "name":"BG2", "value":"art/toombg_para_01.png" },
	{ "name":"BG3", "value":"art/toombg_para_02.png", "anchor_y":560-400 },
	{ "name":"BG4", "value":"art/toombg_para_03.png", "anchor_y":304-400 },
};

Unlike JavaScript though, all member names have to be wrapped in strings to use the colon syntax (i.e. in JS, “name” could be just name).

Alternatively, the Squirrel way is as follows:

ArtFiles2 <- [
	{ name="Man", value="art/anim.png", tile_w=128, tile_h=128, anchor_y=128 },
	
	{ name="BG1", value="art/toombg_bg_01.png" },
	{ name="BG2", value="art/toombg_para_01.png" },
	{ name="BG3", value="art/toombg_para_02.png", anchor_y=560-400 },
	{ name="BG4", value="art/toombg_para_03.png", anchor_y=304-400 },
];

At the moment of this writing, I’m undecided, but leaning towards the JSON syntax because the hardcoded data will be portable to JavaScript. Function syntax for JavaScript and Squirrel is identical, so porting code between the two may simply be a matter of fixing global scoped things, converting var‘s to local‘s, and any in‘s to hasOwnProperty calls… well, constants/enums/operators aside.

Generated String Indexing

This works the same as JavaScript.

SomeData <- { Truthy=true, Other=15, States=[1,2,3] };

if ( SomeData["Truthy"] ) {
    // This is the same as SomeData.Truthy, except //
    // you can feed any string in //
}

Text <- "Other";

if ( SomeData[Text] > 12 ) {
    // Indexing with a variable //
}

print( SomeData["States"][1] ); // Output: 2. Could also do SomeData.States[1] //

Pseudo Inheritance with Delegates

Squirrel does support classes and inheritance, but it also supports an interesting alternative called Delegates.

Tables can be assigned a Delegate, i.e. a parent Table. Delegates are used to assign Metamethods (i.e. overloaded operators) and default values.

Player <- { 
	name="Gentlemen",
};

print( Player + "\n" );

// Output: (table : 0x00580F18)

That’s not a very useful output. Using a delegate:

Character <- {
	_tostring = function() {
		return this.name;
	},
}

Player <- { 
	name="Gentlemen",
};

Player.setdelegate( Character );

print( Player + "\n" );

// Output: Gentlemen

That’s better.

Metamethods (operators) only work using Delegates. So while you are able to add a function called _tostring directly to the Player Object, Metamethods will only fire if they are inside a Delegate.

Default values using Delegates

If we add a member variable to the delegate, the child implicitly gets it.

Character <- {
	_tostring = function() {
		return this.name + " " + state;
	},
	state=0,
}

Player <- { 
	name="Gentlemen",
};

Player.setdelegate( Character );

print( Player.state + " " );
print( Player + "\n" ); // implicitly calls tostring //

// Output: 0 Gentlemen 0

Finally, adding a value to the child (Player) uses its value instead.

Character <- {
	_tostring = function() {
		return this.name + " " + state;
	},
	state=0,
}

Player <- { 
	name="Gentlemen",
	state=10
}.setdelegate( Character ); // Can do it this way too //

print( Player.state + " " );
print( Player + "\n" );

// Output: 10 Gentlemen 10

Delegates are like inheritance without classes.

All Basic Types have Delegates

Yes. So says the documentation. That’s how they get their member functions.

Member Function Syntax

SomeObject <- {};

// Synonym for SomeObject.MemberFunc <- function() {
function SomeObject::MemberFunc() {
    // Woo hoo! //
}

typeof operator

Player <- { 
	name="Gentlemen",
};

print( typeof Player + "\n" );

// Output: table

Using Delegates, we can change the returned type string.

Character <- {
	_typeof = function() {
		return "Character";
	},
}

Player <- { 
	name="Gentlemen",
}.setdelegate( Character );

print( typeof Player + "\n" );

// Output: Character

Even in C code, the value returned by the _typeof metamethod will be a string. Type checking is therefor:

if ( typeof MyVar == "string" ) {
    // It's a string //
}

NOTE: Built-in type names returned are lower case strings.

callee() and .getinfos()

callee() returns the currently running function object.

function MyFunc() {
    return callee();
}

print( MyFunc() );

// Output: (function : 0x00470EA8)

To get information about the current function, you can use the .getinfos() method of any function.

function MyFunc() {
    return callee().getinfos();
}

print( MyFunc() );

// Output: (table : 0x00470FF8)

But as you can see above, it returns a table of information. And unlike JavaScript, Table Printing is somewhat uninteresting.

function InfoFunc() {
	local Text = "";
	foreach( name, value in callee().getinfos() ) {
		Text += name + ": " + value + "\n";
		if ( typeof value == "array" ) {
			Text += "  [";
			for ( local idx = 0; idx < value.len()-1; idx++ ) {
				Text += value[idx] + ", ";
			}
			if ( value.len() > 0 )
				Text += value[value.len()-1];
			Text += "]\n";
		}
		else if ( typeof value == "table" ) {
			foreach( name2, value2 in value ) {
				Text += "  " + name + ": " + value + ",\n";
			}
		}
	}
	return Text;
}

print( InfoFunc() );

// name: InfoFunc
// defparams: (array : 0x00571480)
//   []
// native: false
// varargs: 0
// src: fun.nut
// parameters: (array : 0x00571270)
//   [this]

name: The function name.
defparams: The list of default parameter values (if any)
native: Is it a native C function or Squirrel function?
varargs: How many varadic arguments (printf style).
src: What file it comes from.
parameters: Names of the parameters (NOT values, just names).

NOTE: Native C functions return a different set of results. name, native, paramscheck and typecheck.

Missing _tostring pointers

The returned string “(table : 0×00112340)” is actually a sort of error code. It implies that no _tostring member of the delegate is available.

AFAIK, there is no way to get the pointer value of a table from inside Squirrel (on the stack?). I should look in to this some day, but I’m not interested right now.

Standalone Contexts

Okay! This is the important part for engine designers that want to scope things to game objects.

Key things to know:

  1. A Squirrel script file can be thought of as one big function
  2. The default value of “this” is the root table, but that’s only the default

On that note, I’m going to change the definition of one of the earlier examples.

Scooter <- 10;          // Environment Table //
//::Scooter <- 10;      // Root Table (Globals) //
//const Scooter = 10;   // Const Table (Global Constants) //
//local Scooter = 10;   // Stack //

function Hello() {
	if ( "Scooter" in this )
		error( "is in this\n" );

	if ( "Scooter" in getroottable() )
		error( "is on Root\n" );

	if ( "Scooter" in getconsttable() )
		error( "is on Const\n" );

	if ( "Scooter" in getstackinfos(1).locals )
		error( " is on Stack\n" );
}
	
Hello();

// Output: is in this\n is on Root\n

If this is called as is, the current Environment is the root table, so it will find Scooter in both this and the Root table.

To change the environment, wrap this code in a function (or do the equivalent), bind a different environment, then call the wrapper function. The reason we need to bind first before calling is so that all our references to the new environment correctly resolve to the environment, and not the root table.

function MyStandaloneEnv() {
	Scooter <- 10;          // Environment Table //
	//::Scooter <- 10;      // Root Table (Globals) //
	//const Scooter = 10;   // Const Table (Global Constants) //
	//local Scooter = 10;   // Stack //
	
	function Hello() {
		if ( "Scooter" in this )
			error( "is in this\n" );
	
		if ( "Scooter" in getroottable() )
			error( "is on Root\n" );
	
		if ( "Scooter" in getconsttable() )
			error( "is on Const\n" );
	
		if ( "Scooter" in getstackinfos(1).locals )
			error( " is on Stack\n" );
	}
		
	Hello();

	return this; // **NEW**: If you don't return this, all our efforts are wasted
}

MyEnv <- {};
MyEnv = MyStandaloneEnv.bindenv(MyEnv)(); // Bind, then call (the "()" ) //

// Output: is in this

In the example above I’m calling Hello() inside the function, but it can now be safely called outside using:

MyEnv.Hello();

And it will correctly set the Environment to MyEnv

Things to remember:

  1. local variables inside the MyStandaloneEnv function disappear at the end.
  2. ::MyVar syntax is for accessing the root table (globals), not the environment.
  3. Variable search order is local first, then environment, then globals (root/const).
  4. When I said earlier that bindenv forces the “this” to be what you bind no matter what, what I neglected to say is that it only applies to the wrapping function itself. So any functions defined inside your environment, your this’es will work as expected (member, argument to call, or the current environment). If this makes no sense, just ignore it.
Posted in Technobabble | Comments Off

Nice efficiency things about JavaScript

So I’m typically a native C/C++ programmer, and I seem to surprise people when I say I like JavaScript yet dislike C# and Java. What I like about JavaScript is that it does things C and C++ don’t, as opposed to C# and Java that take C++ and as a base and enforce new constraints to “simplify” code. Both C# and Java do improve on C++, but I find the new strictness they impose to be a detriment or intermediary fix. I think if the point make you write code faster, then JavaScript does a better job.

That said, JavaScript does has its flaws and limits. It’s typically limited to the web, but it is the programming language of the web. Still as programmers looking for that programming zen, I think JavaScript is far closer to that zen than many other languages.

NOTE: When I say efficiency, I mean in getting things done, not performance.

JavaScript is not Java. Stop thinking it is!

Not at all. Easily the #1 misconception, but EcmaScript just isn’t as marketable a name as JavaScript.

The main way I like to illustrate how JavaScript took a better turn is when it comes to writing the simplest program you can in the language: The classic Hello World.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

C# too:

public class HelloWorld {
    public static void Main() {
        System.Console.WriteLine("Hello World");
    }
}

Really, it’s just a coding style difference between the two.

To compare, a simple Hello World in JavaScript is:

console.log("Hello World");

One line of code.

It may not seem like much, but I think this is incredibly important.

To compare, here’s the C version:

#include <iostream.h>
int main( int argc, char* argv[] ) {
	printf("Hello World");
}

Yes, the C version is only 1 line longer, but a better parallel would be this:

import System.*;
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

The import line is implied by Java and C#. I’d say the C version makes more sense, since there is nothing implied. Nothing done for you without asking.

That said, auto-importing is good. I’d say JavaScript does this better because everything in the standard library is auto-imported. Not to mention, the code is executed as it appears, so there’s no need for a main function. The entire source file if executed is main.

Languages like Java and C# sometimes get around this initial verbosity with the tools. Your IDE, once you go File->New Project will generate your basic structure for you. And that’s fine, but it’s not really more efficient enforcing a structure/hierarchy when it comes to something simple.

Automatic Types

var Text = "Hello"; // string //
var Number = 25; // number //
var Pie = 3.14; // number //
var Truth = true; // boolean //
var Func = function() { return "Hello"; }; // function //
var Nothing = null; // null //
var MyArray = []; // array //
var MyObject = {}; // object //

This is a bit of a subtle thing, but knowing and dealing with the type isn’t really that important if everything is a number or string anyway. And again, ignoring performance, being able to set a number actually equal to null is nice because it doesn’t waste numerical space (well, the space is already wasted due to everything being a reference). That doesn’t matter though.

Nested Arrays and Objects (Tables)

This is what matters. Because all types are implied based on the values you hardcode, that makes hardcoding a sophisticated structure extremely simple. You’re not wasting time building classes, you’re building exactly what you want, and changing it exactly when you need to. Added a new property? No problem, it’s already allowed, and you can just go implement it.

var ArtFiles = [
	{ name:"Man", value:"art/dude_anims.png", tile_w:128, tile_h:128, anchor_y:128 },
	
	{ name:"BG1", value:"art/toombg_bg_01.png" },
	{ name:"BG2", value:"art/toombg_para_01.png" },
];

I didn’t have to go make a class for the ArtFile Objects, nor did I have to write all permutations of constructors to take only the arguments I wanted. I just hardcoded what I want. In my code that uses the ArtFile Objects, I check if certain properties exist, and if they do do something, otherwise use what I’ve decided is the default.

To use the data it’s as simple as:

console.log( ArtFiles[0].name );

This saves so much time. No fuddling around types, just fill in what you want and you’re done.

That said, I think how we check for missing properties in JavaScript is a tad more clumsy than it should be.

if ( ArtFiles[0].hasOwnProperty('anchor_y') ) {
    // Do Stuff //
}

That kinda makes sense, and we have to do it this way due to how inheritance sort-of works, but it could be cleaner.

For example, in Squirrel:

// Squirrel, not JavaScript //
if ( "anchor_y" in ArtFiles[0] ) {
    // Do Stuff //
}

I think this is a nicer syntax.

Generic Owner-less Functions

function GetMyName() {
    return this.name;
}

This can be created at the global scope, and given to any object.

var ArtFiles = [
	{ name:"BG1", value:"art/toombg_bg_01.png", GetName:GetMyName },
	{ name:"BG2", value:"art/toombg_para_01.png", GetName:GetMyName },
];

And thus called:

console.log( ArtFiles[0].GetName() );

It can also be cleanly applied to any object, without adding it to the object.

var ArtFiles = [
	{ name:"BG1", value:"art/toombg_bg_01.png" },
	{ name:"BG2", value:"art/toombg_para_01.png" },
];

console.log( GetMyName.call(ArtFiles[0]) );

Where the first argument to call is what to use as ‘this’.

Anonymous Functions

var ArtFiles = [
	{ name:"BG1", value:"art/bg1.png", onaction:function(){console.log("AWESOME");} },
	{ name:"BG2", value:"art/bg2.png" },
];

Only BG1 is awesome, so why waste time adding a short global function only used once?

No Function/Variable Prototypes or Externals Required

JavaScript code is executed in linear order. Functions are declared, but unused until called. Therefor, as long as all your functions get defined before the first is called, then your references to each-other work as expected. No funny circular include/extern logic required.

function Parent() {
	return "Parent " + Child();
}

//console.log( Parent() ); // Fail //

function Child() {
	return "Child";
}

console.log( Parent() ); // Okay //

Global Scope

One of the first things you learn about Object Oriented Programming is that the Global Scope is bad. Yes, the Global Scope is bad… a bad place to put local and member variables, but it’s an awesomely efficient way to access things. In C/C++, global variables resolve down to a single pointer reference to where the data is in memory, rather than a pointer reference/offset for every level deep it is. Nobody really cares about the few cycles lost resolving an address anymore, but it’s still worth knowing that globals are fast, and back in the day that was sometimes why you used them.

That said, care must be taken when dealing with objects in the Global Scope. You have to be sure you choose names that don’t conflict with other things in the Global Scope, such as standard libraries. If you can do that, you can end up creating simpler code too.

var Player = new cPlayer(); // Probably best in a GameInit Function, but proves the point //

var RoomBGLayer = [
	{ img:"Couch",x:-320,y:78,onaction:function(){Player.SetState(ST.SIT_COUCH);} },

	{ img:"Table",x:-170,y:78 },

	{ img:"Head",id:"Head2",x:-178,y:78-38,active:false },
	{ img:"Meat",id:"Meat2",x:-178,y:78-38,active:false },
	{ img:"Soda",id:"Soda2",x:-186,y:78-38,active:false },
];

I just told the player to set his “Sit on the Couch” state and animation on the same line of code I defined where the couch is in the world, and what artwork to use.

That is the magic of Global Scope and Anonymous Functions in action.

Need to add a state or property? Add it when needed!

You *could* create a structure to store states, or edit the base class to include a state and default state.

… or you could just add it as needed.

function DoLayerItem( item ) {
    if ( !item.hasOwnProperty('state') ) {
        item.state = 0; // lets say the default state is 0 //
    }

    if ( item.state == 0 ) {
        // Do State 0 //
    }
    else if ( item.state == 1 ) {
        // Do State 1 //
    }
}

DoLayerItem( RoomBGLayer[0] );

For efficiency, you probably want to populate your data with states, missing properties, etc during some initialization stage, but the above demonstrates the point.

TODO: Add More

I’m going to add more examples as I think of them. I blog for me as much as anyone that reads them.

Problems of JavaScript

JavaScript isn’t perfect. No programming language is. I’ve already mentioned my “hasOwnProperty” beef, but there are more.

Problem 1: No Operator Overloading

This is the one crappy part of JavaScript that I just can’t fix. I like having a Vector class, and I like that Vector class to do math easily with operators like +, -, *, and so on.

That said, Squirrel to the rescue.

Conclusion

These are some of the key reasons I like JavaScript. C/C++ does a lot of the same stuff Java/C# does, but Java/C# prove you a better language by constraining and restricting you (one String type, everything a class, everything in specific folders). They also give you a far better set of starting libraries. C/C++ definitely fail at providing a good stock libraries, but that is part of the point.

C and C++ are fundamental, like a better Assembly. You can write C/C++ code and know the assembly it will generate. If you don’t care about the generated code at that level, then that’s fine. I just don’t think Java and C# do enough to provide a core language that’s faster to work in.

Squirrel?

If you ask me about scripting languages, you’ll probably get a glowing recommendation of Squirrel out me. It seems to fix most of the things I don’t like about JavaScript, from having separate Integer and Float types, 32bit instead of 64bit, operator overloading, nicer property checking syntax, and so on.

That said, I haven’t made a serious project with Squirrel… yet.

I have done projects with JavaScript, I really like a lot of things about JavaScript (as you can see above). JavaScript targets the web, which is a huge advantage, but also a disadvantage.

I’ve done some simple experiments with Chrome’s V8. It works, and I like it. But when I’m writing games, I really use vector math a lot… A LOT… HOLY!

So that’s the trade off. I can have a language that’s web compatible (JavaScript), or one more game dev specific (Squirrel). Using Squirrel does keep me off the web (unless using NaCl, FlasCC, or Emscripten). I dunno. Web technology is in a bit of flux right now.

That said, I like JavaScript. It’s different enough from C/C++/C#/Java that it can do some things better.

Posted in Technobabble | Comments Off