Writing WordPress Plugins and Hooks

Original can be found here

Hooks: why?
————-

When you write a plugin you want to be able to switch it on and off whenever you want. This is not that trivial: say you write a function that does something useful, simply calling the function from your code gives an error when your plugin is deactivated. If you are lucky, it displays nothing, if you are less fortunate it displays all kinds of ugly debug information that people can abuse.

That is why ‘hooks’ were invented. Simply put, a hook is a point somewhere in the generation of your page where you can attach functions. When the hook is reached, all functions attached to it are executed in order of priority. When there are no functions attached to it, it does nothing.

So a plugin should do two tasks:

  • define a useful function
  • attach that function to the right ‘hook’

Many hooks exist already, and most people stick to those hooks. However, hooks are not black magic. Nothing stops you from defining your own hooks, and that is exactly what I’ll do in this page: I’ll create a trivial plugin, put it on my own hook at a place in the page where I like it.

Adding a hook
————–

The first thing I’ll do is the thing many people fear: I’ll create a hook. Using the default theme as an example, the page has a div called "content" which contains the posts in one page. I might want something to happen on the top of the "posts" section, maybe a status message, or a ‘recent comments’ section. That would be the right place to add my own hook.


Now before do that, there is some danger here: many hooks exist already, and before everyone starts defining their own hooks with the same names, let’s set a rule here: if you define your own hook, it should start with your own initials, to let the world know that it works for your plugins and to avoid name collisions. If it is a useful hook, it might become a standard hook for everyone one day.

Ok. Now let’s dive into the "default" theme directory (of course, we work on a backup) and start hacking on "index.php". The spot I had in mind was on line 4, right below the "content" div. I create a hook here called ‘lv_content_head’, because ‘lv’ are my initials, and it is the head of the content. I don’t use any parameters for now.

Below line 3 of "index.php", right below the "content" div, add the following line:

< ?php do_action("lv_content_head"); ?>

That’s all. If you load the page, you’ll see that nothing special happened. That is as it should, because there are no functions attached to it yet.

Now let’s write a "Hello World…" function.

A "Hello World" function
————————-

Now let’s create a real plugin; the file is called "helloworld.php", which will go in the "plugins" directory. The function is plain php; the "Plugin Name" entry in the commented section is is mandatory.

< ?php
/*
Plugin Name: Hello World
*/
function helloworld() {
echo "Hello World…";
}

Now if you would add the closing php-tag, you could see it already in the plugins part of the site administration. Right now, it is not a plugin yet, because it merely defines a function. The next step is to put the function on the hook. Keep the editor open!

Attaching a function to a hook
——————————

Just now we did two things:

  1. we created a hook somewhere in the generation of the page, and
  2. we created a function that is to be called when the hook is reached.

The next step is to attach the function to the hook. This is done by calling the function add_action, where its first parameter is the name of the hook (‘lv_content_head’ in our case), and its second parameter is the name of the function (‘helloworld’ in our case).

Our editor is still waiting for us, so add the function to the hook, and close the php part:

add_action("lv_content_head", "helloworld");
?>

Now the entire plugin looks like this:

< ?php
/*
Plugin Name: Hello World
*/
function helloworld() {
echo "Hello World…";
}

add_action("lv_content_head", "helloworld");

?>

Call it helloworld.php and put it in the wp-content/plugins directory.

From the admin panel it can now be activated, and it should display "Hello World…" on the top of the content area.

A few more pictures from Canada

I finally managed to pry a few more pictures off of my cellphone. This is Kiko, Chris, Franz & I celebrating Chris B’s birthday at a very good restaurant: Banzai sushi. I still owe him a present though… (not that seeing me wasn’t present enough mind you…) ps. Franz was kind of enough to treat Kiko and I to dinner. Thank you!! (my brain was not working, and I apologize, but upon reflection I could have used that as an opportunity to give Chris a birthday present and pay for his dinner. d’oh. chris, forgive me!)

 

chrisfranzdavidcanada2005.jpg   davekikojuly2005.jpg

The Sunflower Parade

I thought this post was going to be more exciting… (as you can see we have the first ever baby name poll happening to your right, SO VOTE!) but things have been pretty hectic. emoticon

We are finally getting over our jetlag, and even though my school visits are over until September I am preparing for the arrival of the new JET‘s to Japan as a member of the Tokyo Orientation Committee and the Kagawa Orientation.

This Friday I also have a Jamaican Cooking day in my town. Apparently I am in charge so I am going to try and make something resembling Jamaican cooking. They also are trying to get me to sing some Bob Marley… umm… no.

Other than that, I am reading Harry Potter 6 (yeah!) and am getting ready for a busy summer:

  1. July 30th to August 3rd: Tokyo Orientation (in Tokyo)
  2. August 5th: Kagawa Orientation
  3. August (dunno): Interning at the Canadian Embassy in Tokyo (yeah!)
  4. August 25th: Kagawa Orientation #2
  5. Rest of my life: Baby.

My town is known for sunflowers (and frogs, and rice, and being a really small town) and their festival was actually a lot crazier than I thought it would be. Take a look! (click on the picture to go to a gallery.)

2005 Sunflower

Here is a picture of me being a Japanese ninja archer from like 2 years ago. I ran into it on my computer a few days ago. I’m cool. 

I am a Japanese Ninja

Summer in Canada 2005

We are  back in Chunan!!! … and have begun the process to get rid of as much jetlag as possible. We both had a fantastic time back in Canada.

I had a scholarship interview that went fantastic emoticon(I’m gonna need something to do when my contract here ends in 2006/08 or 2007/08.) and we got to see a number of really good friends. That being said, we were completely strapped for time, and for everyone that we were able to see, there were 2 more people we would have loved to but couldn’t. Between my scholarship interview in the first week, my Dad’s operation in the second (he’s ok!) and the fact that we only had 10 days in Canada, we did our best.

For those that we did see: Thank you!!! We had an amazing time. emoticonFor those we didn’t: Next year, February. emoticonWe miss you all, and unfortunately because of the baby, this will be our only trip to Canada back this year. Next year we will be back with Baby Awesome (or whatever he/she is named at the time.)

In the meantime, here are a few sample pictures of what we did while back in Canada, and the full gallery can be seen by clicking here.

Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture   Canada 2005 Picture

Atari 2600 Development

Original available here.

 

Inside the Homebrew Atari 2600 Scene

by Howard Wen

"Have you played Atari today?" was an ad jingle for the Atari 2600 VCS game console during its reign in the early years of the video game industry, from the late 1970s to early 1980s. That question that could apply even now, thanks to the passion of programmers who’ve continued to make new Atari games for the past few years. These "homebrew" games come in cartridge form (for use on actual Atari 2600 consoles) and have free public releases as code that runs on Atari 2600 emulators. (Homebrew developers use two of the most popular emulators, z26 and Stella, to test their games.) Emulators have greatly increased the audience for homebrew games outside of those who still own the consoles.

The Atari 2600 homebrew community is the largest among groups who develop original games for classic video game consoles. (This probably corresponds with the fact that the 2600 was the top-selling console during its time. The 2600 was the first video game system for many gaming enthusiasts who were alive then.) The scene is competitive but friendly, where authors share their expertise, advice, and even source code with one another and with those who are looking to program their own homebrew games.

"It’s a lot of fun, with various trade meets and video game expos organized every year. Homebrew development seems to be taking off more than ever," says Joe Grand. In 2001, Grand released SCSIcide (see Figure 1), the first homebrew Atari 2600 game to use the console’s paddle controllers (a technical challenge to implement for the system). This fast-paced "twitch" game — its theme and gameplay inspired by the inner workings of a hard drive — also has the distinction of being the Atari 2600 homebrew game that has sold the most number of copies in cartridge form — over 200 copies. The 28-year-old, an electrical engineer by trade, resides in San Diego, California.

SCSIcide
Figure 1. SCSIcide by Joe Grand

Nostalgia is a primary, initial motivation for most who homebrew their own games. Many were children during the heyday of the Atari and daydreamed of making their own games for it. A more practical reason is the challenge; it takes a certain finesse, and patience, in coding ability to make good games for the decades-old system.

The Art of Minimalism

Programming the 2600 is the art of dealing with limitations. Developers must find ways to optimize for speed and limited memory space. The system has no video buffer, the total code size cannot exceed 4K and can only use 128 bytes of RAM, and, adds Simon Quernhorst, "you even have to share that with the processor stack. This means that occupying too much memory results in crashing programs, as you might have deleted some information used by the processor."

Quernhorst, a 28-year-old IT consultant in Wesel, Germany, created the puzzler Mental Kombat. At present, he is making another Atari 2600 homebrew game, based on Aztec Challenge, a 1983 game originally for the Commodore 64 home computer.

In terms of graphics and sound, the Atari only has two sprite objects — each just eight pixels wide. The background is restricted to 40 pixels per scanline. There are only two available sound voices.

To hear these homebrew Atari programmers put it, these very technical constraints make programming the system … fun?

"It’s a lot like working a puzzle," Paul Slocum describes, "and there’s something satisfying about working so closely with the hardware [and] not having layers of software between you and the CPU." Slocum, 29, lives in Dallas, Texas, where he works as an embedded systems programmer. He wrote Marble Craze and Synthcart, a program that produces music on the Atari 2600. (He even uses the Atari as an instrument in his own band.) Currently, he’s developing an RPG officially featuring characters of the cult online animated series, Homestar Runner.

"I’m still attracted by the simplicity of gameplay, graphics, and sound. It’s the art of minimalism," says Quernhorst. "The limitations of graphic registers, RAM, sound voices, and colors increase the challenge of getting nice results."

"Because the Atari 2600 hardware is so limited, you must concentrate on the gameplay," emphasizes Thomas Jentzsch, who has created two homebrew games for the Atari — Thrust and Jammed. The 39-year-old is a software developer for a mobile phone company in Düsseldorf, Germany. "The gameplay must be as perfect as possible. Then the player will soon forget the limitations of the system. That makes the biggest difference between the classic games and many modern ‘games’ that concentrate way too much on eye and ear ‘candy,’ and often neglect the gameplay dramatically."

Bits and Bytes

The tools needed to make games for the 2600 are surprisingly simple. There are only three: a text editor (many Atari homebrew game developers recommend TextPad), a 6502 cross assembler (such as DASM), and one of the aforementioned emulators (z26 or Stella) to test the code.

The programmer’s skillset is more important. Developers need very good familiarity with the 65xx assembly language in order to understand the architecture and addresses that set the sprites, read the input devices, play the sounds, and do everything else on the 2600.

"You must love dealing with bits and bytes, because the Atari 2600 requires 100 percent Assembler coding," warns Jentzsch. "And you need some perseverance; often, coding is quite frustrating and sometimes a solution for a problem seems to be almost impossible. There are far more abandoned than finished projects for the Atari 2600, mainly because the programmer burned out."

"It’s not actually that tough a technical challenge to program the machine. But programming it efficiently and effectively is what separates the experts from the rest," says Andrew Davie, a 40-year-old professional programmer in Hobart, Tasmania, Australia. Davie developed the game Qb (Figure 2), as well as many technologically innovative programs for the Atari 2600 that other homebrew authors have put to use, such as Interleaved ChronoColour, which brings full-color bitmap capability to the machine. He’s also written several articles guiding newbies on how to program the 2600.

Qb
Figure 2. Qb by Andrew Davie

Playing the final product on an actual Atari 2600 system requires that the code be burned onto RO

M chips. Those who are not interested in figuring out the intricacies required to do this can usually seek out assistance from others in the Atari 2600 homebrew scene who make game cartridges for the system. The easiest and quickest way to test homebrew code on an Atari is the Cuttle Cart, is a cartridge that can hold downloaded code.

"There’s nothing like playing a game on the real hardware using real controllers — emulators can only get you so far," says Grand.

Thanks to emulators and the processing speed of modern computers, the development process for making Atari 2600 games is far more convenient and faster now than it was for those programmers on staff at Atari back in the late 1970s. One advantage they had over present-day homebrewers, though, was the availability of better debugging tools. The members of the Atari 2600 homebrew scene make up for this by relying upon each other’s advice and assistance.

"The hardware, simple as it is, is still not fully understood [by us]," says Davie. The homebrew scene learned yet more about the Atari when one of the companies that previously owned the Atari name released additional technical information to the public. "It’s only since the circuit diagrams for the TIA chip [a central component of the Atari 2600] have been available, and since some clever individuals started analyzing the operation of the chip, that we’re coming to understand why the hardware behaves as it does — and how to use this knowledge to make effective programs," says Davie.

Display Kernel Issues

Besides the 2600’s limited amount of memory, homebrew game developers say that the most difficult aspect about writing software for it is dealing with its display kernel. Since the system lacks video RAM, each scanline must be programmed directly. The picture on the screen has to be drawn in synchronization with the video beam, which can be a tricky feat to pull off, and there are only 76 CPU cycles per scanline. The game code must also control vertical synchronization, repositioning the electron beam at the top of the screen to start a new frame.

"Following the raster beam, you have to set each pixel and color just in the right moment to show it. If you want to show a sprite from lines 50 to 60, for example, you have to set the sprite values by hand at exactly the scanlines 50 to 60 on the correct horizontal cycle," explains Quernhorst. "This makes variable sprite positioning quite difficult. Such things are much more easy on other machines, as you can simply set the X or Y values to their registers at any time during your program."

To squeeze out the best screen display under this restriction, the display kernel usually has a unique design for each game. The display for an action game, where objects on the screen move quickly, would need to function differently from that of a puzzle game, where the objects would probably be static.

"You have a limited amount of time [for] each TV frame to do game processing before you have to start drawing the screen again. So you have to guarantee that under all conditions, your game-handling code will finish within that amount of time," says Slocum. "This can be tough since you usually have to cut it close."

Another issue with the 2600’s display is that the color order and location of the data bits on the screen are randomly selected. This routine is a time-consuming function which, if not executed properly and placed in the right section of the code, can result in annoying flickering of objects on the screen. For his game, Grand says he made the decision "to run the routine once at the beginning of each level, which led to a quick flicker of the screen. This way, gameplay wouldn’t be noticeably affected by flickering every time a data bit was read."

New Games for Old Systems

All of this extreme, stripped-down simplicity does have one benefit: making a game can be a one-person effort. "Game development projects for old machines can be done by single developers, while modern game systems require a lot more manpower, if you want to make state-of-the-art games for these platforms," says Quernhorst." It’s almost impossible for a single person to create a cool game on a modern platform. It’s easier to develop cool games for the ancient machines due to their limitations."

Ultimately, it’s more than just the challenge that attracts programmers like Quernhorst and his colleagues to make new games for the Atari — or for any classic game console. There’s a passion and love, not only for the systems themselves, but for the community of fans who have been helping the old hardware remain relevant today.

"It really feels good to know that the time, frustration, and money spent to develop and manufacture the game was all worth it. It’s nice to give back to the community and provide people with a new game for an old platform," Grand says.

The Developers Speak

Homebrew game authors Andrew Davie, Joe Grand, Thomas Jentzsch, Simon Quernhorst, and Paul Slocum discussed with the O’Reilly Network their experiences in making games for the Atari 2600.

O’Reilly Network: What inspired you to make your own Atari 2600 game?

Andrew Davie: I had many games under my belt, but only as programmer/designer. I’d not had the opportunity to develop a full product from concept through programming, marketing, and sales. I saw the 2600 as an ideal platform to do all of these in one go. I also happen to adore the 6502 processor — the Atari has a variant of this, and was fascinated by the technical challenge of getting the machine to do anything, let alone something interesting. I was originally motivated by Bob Colbert’s pioneering work on Okie Dokie.

Thomas Jentzsch: I must admit that I had almost completely forgotten my Atari 2600 when I accidentally found a working emulator for it on the Web. But almost immediately I remembered the fun I had back then. Soon after that, I found the Stella developers group and saw a new challenge for my Assembler programming hobby.

Simon Quernhorst: I’m a collector of Atari VCS cartridges for years now, and I decided to start a development project in 2001. I’ve been programming demos and games for the Commodore 64 for years. Therefore, the machine language of the VCS was nothing new to me — just different addresses had to be learned and checked. (Quernhorst created A-VCS-tec, as seen in Figure 3.)

A-VCS-tec Challenge
Figure 3. A-VCS-tec Challenge by Simon Quernhorst

Joe Grand: I was already collecting cartridges for the Atari 2600, and I wanted to work on a project that combined my hobby and my professional life — electrical engineering. Not only did I code the game, but I created a custom circuit board. The boards fit into the standard Atari cartridge cases and all components are easily obtainable at many electronics stores. This made the manufacturing process much easier and less frustrating. I built the first 50 games by hand to sell at a gaming expo and sold out almost instantly.

Paul Slocum: The challenge of programming for such a minimal system, and I really wanted to when I was a kid. I actually still have game designs I drew up in elementary school, although I don’t think many are feasible on the 2600.

O’Reilly Network: What’s your personal favorite Atari 2600

game? Why?

JG: Activision’s Kaboom!. It’s the type of game that forces you to get "into the zone" and just space out. It’s a very "Zen-like" game. It was the inspiration for SCSIcide.

AD: I don’t really have a favorite. I am mostly interested in the technology, rather than the game itself. Having said that, Dig Dug was a very good conversion effort, so I’m partial to that at the moment. Many of the modern homebrews are excellent.

SQ: I’d mention H.E.R.O. It’s really good and was well-designed overall. I also enjoy most of the modern homebrew games. Just to mention a few: Qb, Star Fire, Marble Craze, Merlin’s Walls, and Thrust (Figure 4).

Thrust
Figure 4. Thrust by Thomas Jentzsc

TJ: From the classic period, Starmaster. It was one of the very few games I owned, and it combined action with some strategy. I was very addicted to the game back then.

From the modern homebrew games, Oystron. This was one of the first homebrews I found, and it is a great game. It was Oystron that made me want to program my own game. It defined a new level for Atari 2600 homebrewing and showed that a homebrew game could match the old classics.

O’Reilly Network: What interesting technical challenges did you came across when you made your game?

PS: I made it extra hard on myself by doing a paddle game. Paddles must be read while displaying whatever’s on the screen, and timing is critical during the display. Since SCSIcide was the first homebrew game to use the paddle, there was no previous work to reference.

One byte of RAM was used to store the current numerical value of the paddle. At the beginning of each frame in the vertical blank, the capacitor inside of the paddle controller is discharged and, a few cycles later, set to recharge. During every scanline draw, the value of the capacitor is read. How long the capacitor in the paddle takes to charge determines the vertical position of the [player character] on the screen.

For example, less resistance in the potentiometer of the paddle will cause the capacitor to charge more quickly, and place the [player] towards the top of the screen. If the paddle is moved in the other direction, increasing the resistance of the potentiometer, the capacitor will take a longer time to charge, and the [player] will be placed lower down the screen. Programming efficient and "non-fluttering" paddle control took the longest amount of development time and required a great deal of experimentation with the Atari 2600 system.

SQ: The Atari VCS can only handle banks of 4kb at one time, and a technique called "bankswitching" is used to access more ROM. You can tell the machine which of the 4kb banks is currently in use and access this ROM then. The problem is that the memory is always numbered in the same way. This means that an address $0F00, for example, is used two times; once in Bank 1 and once in Bank 2. When jumping from one bank to the other, the processor jumps into Bank 2 at just the address where you left Bank 1. For example, a bankswitch command at $0E03 in Bank 1 lets the processor continue at Address $0E06 in Bank 2.

O’Reilly Network: Did you develop any unique code that takes advantage of the Atari 2600’s technology?

TJ: For Thrust, I invented a smooth looking, bi-directional "delayed" scrolling that is still quite unique for the 2600.

JG: My proudest achievement was implementing the paddle support, but I also created a six-digit hexadecimal scoring routine based on some old score display code, and implemented a cool random number to generate the random color and location of the data bits on the screen.

AD: The Interleaved ChronoColour technology was independently developed, but does duplicate similar technology already available on other machines. It introduces "full-color" bitmap images on the Atari 2600, where previously only single-color-per-pixel images were possible. This has extended the graphics capability of the 2600 significantly. The technology involves real-time multiplexing, in time and space, of red-green-blue-component images to achieve a color image.

SQ: I invented a PAL/NTSC-switch on Mental Kombat. As far as I know, no other game now uses this technique. This makes the cartridge run on any machine worldwide without problems or mixed-up colors.

PS: I’d say my most innovative work was with music. I wrote a music driver that managed to do fairly decent music in spite of only having two sound channels and very limited pitch. And the driver uses very little processor time, so you can easily run it in the background in-game.

O’Reilly Network: What advice do you have for others who are interested in making their own homebrew games for the Atari 2600?

SQ: If you already know assembly and machine language: take a lot of time and patience and prepare for a very exact programming challenge. The 2600 is very timing-sensitive. Using too many cycles in one scanline may, for example, lead to mixed-up graphics and colors. In very timing-sensitive routines, counting the cycles of every operation by hand might help to ensure that you’re not using too many cycles.

JG: Experiment, experiment, experiment, and be patient! There are a huge number of resources available now that provide disassembled games, commented source code, development tools, emulators, and discussion lists.

It might appear easy, since there are so many homebrew game projects going on right now. But take small steps and play around a lot. That is the best way to learn. There are lots of people in the community willing to help out new developers.

Writing a game takes time, as does thinking up graphics and packaging, making the cartridges, etc. You won’t make a quick buck, so only do it if you love it.

2600 Homebrew Resources

 

On Our Way

yo.

Just a quick note… we are on our way! I am writing this at 5:32am and we have to be at the airport by 6. I have a sore throat, Kiko is large, and our suitcases are super heavy.

We will be posting a lot about our time in Canada, pictures, some amazing times seeing good friends and family, pictures of my good friend Mike and his new baby, and lots of other excitement. In the meantime, we have a 20+hr transport looming ahead of us, so wish us luck.

We will be missing everyone in Canada terribly, but I have to get back and water the watermelons… or something.

Look for pictures soon…

love david & kiko.

The Big News

Why is Kiko so large-ish in the previous entry???emoticon

Drumroll….

   Both Kiko and I would obviously like to be able to give everyone the good news face to face, but since that really isn’t much of an option, we want to take this opportunity to let all of our good friends and family (and the stragglers from the internet who accidently find themselves here… i guess) know the good news…
Introducing David Jr. aka Kunio aka We don’t have a name yet! emoticon

 

Now accepting name submissions. There will be a vote. You can forever improve or mess-up it’s life. Make it so.

 

davidjr.jpg 

 

 

Kiko & David! & Off to Toronto

Just a quick note before we set off for Toronto. It will be a very short and action packed filled trip as we head back to Toronto for 10 days. I have a big scholarship interview but after that is done (30th) I hope to see as many people as I can in the last 4 days. Wish me luck!

See you guys soon and wish us a safe flight! …

Kiko’s New T-Shirt 

No matter what she tells you, this is Kiko’s new favourite shirt. (you can tell by how happy she looks in it!!) 

Another big thanks to Chris and Lianne! Everything you guys have sent has been amazing…. miss and love you guys.  emoticon 

kiko-and-david!1.jpg 

 

 

I Love… Dokdo?

Time to give you a little insight into the region where Kiko and I are living.

Japan wasn’t exactly the most popular country right after World War II. After invading the rest of Asia (to save it from the whiteys… who else?) many of the regions they had taken over were being claimed by various countries. (Mostly China, Korea etc…)

Fast forward to 2005. There is this tiny little ass island called Takeshima in Japanese, and Dokdo in Korean. Now Japan (The Country) claims it as their own island, while Korea claims it as theirs. For some unknown reason Korea got a little excited about this and made a big deal about it. After 3 Korean people cutting their fingers off, 40 Korean’s moving to the island, Korean TV Shows & Movies about Imperial Japan, and 130million Japanese people going "… we have an island called Takeshima?" emoticon Read, learn, and become smarter here.

edited: Wow. After a little searching I found this. Koreans seem pretty excited about these rocks. Welcome to Cyber Dokdo.

I am proud to present my "I love Dokdo" shirt from my very good friends Chris and Lianne in Korea.

I wear it around Japan, but they just laugh. They cannot fathom why there are "I love Dokdo" goods selling in Korea, and the average Japanese person would be more than happy to give it back…

 

dokdo.jpg 

 … and yes those are I love Dokdo socks and a pencil case.