Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (489)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (553)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2 3 ... 34
1  Game Development / Newbie & Debugging Questions / Re: [solved] Updating & Rendering in a timely fashion on: 2014-08-31 04:04:57
@SHC
I always found that quote from Eli to be very puzzling. So, util.Timer was not intended for heavy-lifting? How can a person tell this? It's just code. Nothing in the API warns about this, nor anything in Joshua Bloch's well-documented source code for the class. Code in the TimerTask runs the same as code in a game loop, as far as I can tell, though they rely on different native routines (wait vs sleep).

@BurntPizza
...doesn't the exact same thing happens when update() and render() take more than the allotted time: the next iteration simply gets pushed back? This is the same with the ScheduledExecutorService (as you configured it), with util.Timer and with a game loop. Yes?

But if the NEXT iteration after that takes less than 16 millis, with either the scheduler or timer's .sheduleAtFixedRate(), an attempt to recover the lost time, gratis, no extra coding needed.

I suspect that the poor reputation util.Timer has vs. coding one's own timing mechanisms into game loops has an element of "herding behavior" to it or some sort of echo chamber effect. I have yet to read one rational explanation or see a concrete example that justifies the preference. I point out again, even "Killer Game Programming" from way back when gets the same performance with util.Timer as with their preferred game loops, and then says well, we are going to stick with writing our own game loops anyway. (The book does an excellent job of demolishing the swing.Timer, though!)

But this is okay. It probably doesn't make a bit of difference, and my harping on this is an example of I don't know what. I certainly don't want to try and tell other people they should convert their game loops to TimerTasks.
2  Discussions / Miscellaneous Topics / Re: Music in games? on: 2014-08-30 04:36:13
I haven't really researched this as much as I should, but I think that sometimes a game maker and a composer can work out a mutually beneficial arrangement. For example, the game maker is allowed to use a piece, but provides links to the composer's site or to a place where the game player can buy an mp3 or song file that is an arrangement or version of the game music.

The one example I recall like this was in a game called "Entanglement".
http://entanglement.gopherwoodstudios.com/
Somewhere on their site, if I remember correctly, they talk about the music and give a link to the composer's site where a purchase can be made. They may have payed a small fee upfront. I can't recall the details--it was a couple years ago when I found this and filed it away as something to eventually try out myself.

The music for that particular game is NOT what you described as would fit your game. But maybe if the composer finds those sorts of deals work, chances are the composer can also write something more along the lines of what you are wanting.

If that doesn't work, or you find yourself still looking for music a few weeks from now, I have a special case situation that could allow some sort of trade off. I've been working on a procedural music engine, and am looking for an opportunity to give it a go. Your post reminds me of a poppy, driving synth piece I wrote a long time ago (played it in a rock band in the 1980's actually, but that band didn't make it out of the garage) that I think is exactly the sort of thing you describe. But this isn't a situation where I'd just record it and hand over cues. I want to have the game play the score procedurally. So, your game would have to have some slack processing capacity, and you'd have to have some time. (We'd work out an api between us customized for your game, and I'd supply the needed libraries.)

A very simple working example of the procedural music engine is at this link:
http://www.java-gaming.org/topics/tanpura-drone-tuning-training-jar/34132/view.html
If you listen to the "SquareWave" and "Sawtooth" synths, and imagine that sound with a really punchy attack instead of a slow fade (very easy for me to reprogram their envelopes), those are two synths that can be run for pretty cheap (just two FM oscillators). I've also managed to get flanging/chorusing working and that does a great job of thickening textures. Of course, a circle of notes is a lot less interesting than a good rhythm, but this audio event system I wrote is capable of solid rhythmic precision. As I wrote on that post, that drone tool is a stepping stone project.

Ah, there is a lot here I really want to get to! If not your project, maybe in a few more weeks I'll have a better demo of what I'm talking about, and a proposal like this won't be so speculative. Cool But also, there do remain unproven aspects--I still need to tighten up the coding so it uses less cpu.  Emo
3  Game Development / Newbie & Debugging Questions / Re: *solved* Updating & Rendering in a timely fashion on: 2014-08-29 23:57:02
Quote
using Swing or other "timers" is fine. all of them use System.sleep(1) anyway.
@basil_
Well, sort of. The util.Timer relies on native code implementing Object's wait(long) method. It is set to a value that corresponds to the schedule of the next TimerTask on its internal queue. Thus the wait is probably larger than 1.

Thread.sleep(1) uses native code for sleep(long).

But both do make use of the System Clock which is either limited by larger of the granularity of the milliseconds input parameter, or by the minimum interval at which the clock is updated (about 16 millis for some older Microsoft OS).

I don't think the util.Timer adds much in the way of overhead. The most significant addition is a very nifty queue implementation set up for the TimerTasks (I think it's set to a simple array of 128 unique tasks), but it is a model of efficiency (written by Joshua Bloch). I would guess having a single wait(long) is probably better than multiple calls to sleep(1). But these are quibbles to your main point.
4  Game Development / Newbie & Debugging Questions / Re: *solved* Updating & Rendering in a timely fashion on: 2014-08-29 07:38:08
Quote
Never, Never use Timer and TimerTask for game loops, they are mainly designed with Swing in mind and may not work well for a gameloop.

SHC -- Could you be more specific about your objections to the util.Timer? I've never had a problem with them, and there is nothing that I know about them that is specific to Swing. AFAIK, you can put any commands you want in them. You're not confusing the util.Timer with the Swing Timer, are you? I would agree that the Swing.Timer is not good for game programming due to performance issues arising from the potential EDT bottleneck.

Eventually, one can graduate to an Executor Service with a fixed schedule--that might be slightly preferable. But that would be a lot to learn for a Newbie. Better to get on with entity management, movement physics, collision detection, etc., imho.
5  Game Development / Newbie & Debugging Questions / Re: *solved* Updating & Rendering in a timely fashion on: 2014-08-28 23:04:24
In this section:
1  
2  
3  
4  
5  
6  
    while (System.nanoTime() < startTime + nanosToSleep) {
        try {
            Thread.sleep(1);
            } catch (final InterruptedException e) { }
        }
    }

...I'm not sure the Thread.sleep(1) command actually does what one thinks it should consistently on all systems. The sleep command depends on the system clock, which is a different time source than that of System.nanoTime(). (API for nanoTime() and Thread.sleep() elucidates this.) If you are on an old version of Windows, it might actually be sleeping longer than that.

Can also try the following:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
// import java.util.Timer
// assumes also a reference to the "game"

    Timer timer = new Timer();
    TimerTask task = new TimerTask();

    timer.scheduleAtFixedRate(task, 0, 16);  

    class GameLoopTask implements TimerTask
    {
        game.update();
        game.render();
    }
}


It might be interesting to put in a counter to check the actual frame rate and compare.
6  Game Development / Game Mechanics / Re: Getting into multi-threading. on: 2014-08-25 21:21:43
I think princec's statement about restricting multithreading to situations that don't require synchronization or have dependencies is a good one. What I want to add is the point that if you learn more about "functional programming" techniques and use them, the set of possible situations that do not require synchronization or dependencies will grow, creating more situations where multithreading can be used without the synchronization headaches or complications.

Example of functional programming strategy: using an immutable object, from the Java Tutorials:
http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
I often use a construction almost identical to this, collecting variables into one object. It's helpful, among other things, for keeping objects subject to multithreading in consistent states, and can work well with the paradigm of separating data/models/presentation.
7  Discussions / Miscellaneous Topics / Re: Best books for programming in general? on: 2014-08-22 23:03:49
LOL for ags1's recommendations!

I'm finding "Clean Code" by Robert C. Hunter helpful. Definitely the newer things I've written that follow his suggestions have proven to be easier to read and modify, and less buggy, than other code I've written.

I'd supplement his approach with learning more about functional programming techniques, but I don't know exactly what to recommend for that. A lot of the FP writing seems to take things to extremes, at least to my spotty programming knowledge and experience.
8  Games Center / WIP games, tools & toy projects / Tanpura / Drone / Tuning-training jar on: 2014-08-22 21:28:48
This is an alpha release of a tool/toy, not a game. The coding that went into it is also a stepping stone towards the goal of writing a real time game music engine. Procedural-generated tones respond to the real time tweaking of the controls, but the data structures used (for game music) could certainly be more sophisticated.

The jar file can be downloaded and tried from here: http://www.java-gaming.org/user-generated-content/members/27722/tanpura.jar



The app produces a drone that can either be used for musical accompaniment or for intonation training. You can specify up to six pitches. I'd allow setting it for more, but the audio/synth processing needs to become more efficient first.

One thing that makes it different from most other drone tools is that it has very flexible tuning/intonation controls, allowing for easy "perfect intervals." It also allows you to tweak the intonation of a given note even further, as is often required when adjusting a Tanpura's tuning to a particular "shruti" of an Indian classical music scale/raga.

I've been using a prototype for intonation practice, setting the cycle to three notes (the tonic, fifth as a perfect 3:2 ratio, and octave) and playing pentatonic scales very slowly (on my oboe), pushing my intonation a little sharp or flat then honing in on the "sweet spot."

In the Options area, one can specify the type of notation used for the notes. I set the default to the Indian solfege system: "Sa Re Ga Ma Pa ..." but Western solfege or functional or interval or even absolute pitch names can be used. Changing the "root" on the front face transposes the entire drone.

Possible names (still deciding):
Shruti Devi (I don't know if this sounds okay to Indian ears--but I do hope to reach Indian musicians)
Drone Maester
Pitch Maester

I intend to put "Save/Load" buttons on the bottom. Was planning to use serialization of the data objects, but I want to first make sure I do this in a way that won't break if the feature set changes down the road!

I hope to add a couple more synths, e.g., a string synth patch. I also hope to improve the audio/synth engine performance, as there is stuttering when pushed.

Am open to more suggestions!
9  Game Development / Newbie & Debugging Questions / Re: Draw on an empty image... on: 2014-08-13 06:15:53
The usual way to draw and save images is with the BufferedImage object. You can get access to the individual pixels with a WriteableRaster. A BufferedImage can be drawn via the command drawImage.

http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html
http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawImage%28java.awt.Image,%20int,%20int,%20java.awt.image.ImageObserver%29

10  Discussions / Miscellaneous Topics / Re: Life is like a strategy game sort off on: 2014-08-07 07:14:50
These arguments about "free will" trivialize consciousness, which is genuinely complex and problematic. Our actions are the result of many forces, most of them embedded in the environment and in over-learned, habitual behaviour, with only a tiny portion of consciousness able to review and try to change course. That ability is limited, and that ability is the most interesting aspect of "free will" to me.

If you want to consider something really interesting, check out the following article.
http://www.plosone.org/article/info%3Adoi%2F10.1371%2Fjournal.pone.0016782

Experiment 1:

Subjects are given two paragraphs to read about a growing crime problem in a city called Addison. After they read the article, they are asked to make suggestions as to what might be done to address this problem. The answers differed measurably, affected by an embedded metaphor in the two paragraphs. Only a tiny fraction of the people taking this experiment listed this metaphor as having contributed to their reasoning process.

The paragraph was as follows:
Quote
Crime is a {wild beast preying on/virus infecting} the city of Addison. The crime rate in the once peaceful city has steadily increased over the past three years. In fact, these days it seems that crime is {lurking in/plaguing} every neighborhood. In 2004, 46,177 crimes were reported compared to more than 55,000 reported in 2007. The rise in violent crime is particularly alarming. In 2004, there were 330 murders in the city, in 2007, there were over 500.

Folks that read the "wild beast preying on" version tended to come up with "capture/enforce/punish" suggestions (e.g., hire more police, build more prisons, lengthen jail terms). Folks that read the "virus infecting" version where more likely to have "diagnose/treat/inoculate" suggestions (e.g., look for root cause, try to fix economy, improve education)  than the first population.

That's two measurably different responses on the conservative/liberal spectrum. Results were independent of politics, age or gender. In other words, self-identified liberals tended to suggest more of the punitive suggestions if they read the "wild beast" paragraph, and vice versa.

It is kind of astonishing to me how much the metaphor, a silly figure of speech, can have such a profound effect on the responses of people without them being aware of the manipulation.

You want to talk about "free will" and whether a brain can affect the position of atoms? I think it would be more pertinent to talk about our susceptibilities to such manipulations, to the strengths and weaknesses of conscious awareness. If you don't think this is much of an issue, I would point out that there are major think tanks devoted to crafting metaphors to use to frame discussions and thus influence political outcomes. We are subjected to this stuff all the time. We have it in out power to become more aware and less susceptible. That to me is a more important aspect of "free will." I really don't like the idea of being herded about this way or that without even aware of it.
11  Discussions / Miscellaneous Topics / Re: Life is like a strategy game sort off on: 2014-08-06 17:47:28
well i think it is like a strategy game, if you make the right choice/pick the right path you succeed, if you make the wrong choice or path you lose and got to face with the consequences of wrong thinking.

so before you make your choice, look at the consequences! Smiley

what do you think life is?

A really great game will either provide a rich mine of metaphors and ideas that one can apply to one's life, or it will be a much appreciated escape from the same.

There's no way of knowing how a strategy game's paths are mapped. There can be many different roads to success. The game can be tight or easy. There can be possibilities of redemption built in, or sudden death. A lot more depends on the game than the choices made.
12  Game Development / Newbie & Debugging Questions / Re: Why does my if statments stop working when I remove System.out statments on: 2014-08-01 18:37:56
@Kevin - I think you are right about this example. I just got triggered by the mention of Swing.Timers.


13  Game Development / Newbie & Debugging Questions / Re: Why does my if statments stop working when I remove System.out statments on: 2014-08-01 07:10:34
Yikes! Since when is it recommended to do the "update" part of a game loop on the EDT?  Shocked  The presentation layer has plenty to do without having to do updates as well. You lose multi-core benefits if everything is done on the EDT. This is a big reason why the Swing timer is so terrible for getting good frame rates. "Killer Game Programming" has a classic comparison of game loops versus the use of the util.Timer versus the Swing.Timer, and the Swing.Timer gets clobbered big time. It's really not a recommended option for a game loop control. (util.Timer passes their tests, though).

Ideally, the game loop update() code should not act on any Swing components directly. It should only be acting on the "model" layer, the underlying data. Sometimes we get lazy and and use the .value method of a given control, rather than posting that value to a model-layer variable. Sometimes we get away with it, other times it leads to debugging headaches.

The render() code (aka "presentation" layer) can refer to the model data as needed to determine how to render, but it should only read, never change anything at the "model" level. The render code can/should all be on the EDT. AFAIK this happens automatically when you act on a Swing control.

When I first saw the code you wrote, I was highly suspicious of some of the practices such as executing a function within the println method. It is kind of asking for trouble and difficult debugging. That function could easily be hiding side effects. If that function changes anything in your underlying data or game state, then deleting or commenting out that comment could have very unpredictable effects.

There is a really good book on Java coding style that I'm re-reading at the moment. I highly recommend it. The emphasis is writing code that you (or anyone else) can read and debug easily, even 6 months or 6 years after the code was written and it is stone cold in your mind.

Robert C. Martin "Clean Code -- A Handbook of Agile Software Craftsmanship"
14  Game Development / Newbie & Debugging Questions / Re: Paulscode - Soundsystem - Load from bytebutter? on: 2014-07-31 23:24:44
I had to search "wad file architecture" and found a reference to Doom. Is that what you mean?

How are you creating your jar? From an IDE?

If you are doing it from a command line, you can do so with the following syntax:
From: http://docs.oracle.com/javase/tutorial/deployment/jar/build.html
1  
jar cf jar-file input-file(s)

input-file(s) can refer to a folder. But I've never done it this way. It might be a bit tricky figuring out exactly how to address the file via getResource() method.
15  Game Development / Newbie & Debugging Questions / Re: Paulscode - Soundsystem - Load from bytebutter? on: 2014-07-31 21:40:48
Maybe I don't understand the question. If your audio resources are in a subfolder of the source code, then it should be automatically packed inside of the jar.

For example, I have a package called pfaudio. In it is a class which is used to play wav files. The package also has a subfolder "audio" which has wav files in it.

The code used to get the wav file follows:

1  
2  
      URL url = PFAudioMixer.class.getResource(fileName);
      AudioInputStream ais = AudioSystem.getAudioInputStream(url);


where fileName = "audio/Boom.wav" and PFAudioMixer is a class in the pfaudio package.

To make the jar, I use Eclipse's functionality. There is a point in the process where it is possible to check or uncheck specific folders for inclusion in the jar. The default is to include all the subfolders of whatever folder you are in at the time you click on the utility.

A similar thing can be done with graphics resources.


I recall that princec has made the code available for his Titans game, and if I remember correctly, he may have had it setup more like you describe where the files loaded are raw PCM data, not actual wavs. My memory is hazy on that. There was something unusual going on, but I can't recall just what.

TinySound is a decent alternative to Paulscode, and afaik, Finn is still supporting his project.
16  Game Development / Newbie & Debugging Questions / Re: requst for newbie overview tutorial on porting options on: 2014-07-31 19:02:06
 Clueless  Huh  Clueless  Huh  Clueless
Ok, I understand that using LibGDX requires the use of graphics commands that are unique to LibGDX, that are built upon OpenGL. Correct? Now, if you have already written graphics via Java2D in a "core-Java" game, the rewriting for the graphics is kind of a big deal, due to the fact that OpenGL is not exactly object-oriented. There are structural differences. Correct?

If you use Avian as an embedded VM, does anyone know how graphics are done? Avian does not include Java2D. I'm sorry if this is a totally noob question, but I am new to the concept of embedding VMs.

Similarly, several have mentioned RoboVM. Is that also a VM? I got confused and thought that I could use it to crank out code that I could then deliver to an Obj-C programmer. Is it actually a VM that runs Java? The mention there is a Java-to-ObjC bridge, so does that mean one will be required to rewrite the graphics to make use of the graphics commands provided by that bridge? If so, how does that compare to rewriting to LibGDX/OpenGL?

My immediate concern is simple 2D stuff, no 3D.
17  Game Development / Newbie & Debugging Questions / requst for newbie overview tutorial on porting options on: 2014-07-28 21:13:32
It would be nice to have in one place a tutorial on the current porting options (java to android, java to ios).

I'm seeing, for example, in going from Java to ios:

 - hand write code yourself (maybe not a terrible option, given Obj-C has a fair bit structurally in common with Java due to SmallTalk roots, but of course depends on the scale of the game and the use of libraries)
 - Avian
 - RoboVM
 - LibGDX
 - java2objc
 - multistep sort of thing: java to javascript/android, then javascript to obj-c as there are possibly more JavaScript to iOS options than from Java?

But for a Newbie, there is a lot of issues and steps involved that aren't immediately made clear by going to the various home pages for these resources. For example, if an embeddable VM has a reduced set of Java implemented, how are graphics and other IO (sound, mouse, touchpads, etc.) dealt with in each option?

Just an overview would be good, no need to get too detailed.

I'd write it myself if I were capable, but I don't have the needed knowledge. I'm pretty sure there are folks here that are well acquainted with the options and pros & cons of each.

I can guarantee I'd be one of the first to "appreciate" this if it were available. (Maybe there is already link at JGO I've overlooked?)
18  Game Development / Newbie & Debugging Questions / Re: Can someone teach me Perlin Noise? for my 2d game? on: 2014-07-28 20:59:11
Roquen has a great tutorial post here on JGO.
http://www.java-gaming.org/topics/noise-bandpassed-white/27071/view.html

SiVi is an open-source project of mine that uses Ken Perlin's 3rd version of random noise (known as Simplex Noise). There is not a lot of explanation, but it does have examples of different outputs (including a topo map), and a hands-on interface where you can vary parameters and see what effect they have.

SiVi also has a pretty simple working code example in the "help" area with lots of comments, including some notes on how to make a topo map. You can download a jar and get immediate access to this via the following link. http://hexara.com/SiVi.jar

In the below image (not the greatest terrain example, I'll admit), is an example of a mapping to a color bar with 256 increments (on the right) to get terrain. The number ranges and colors I choose are arbitrary. You can define your own for game purposes (e.g., 0 to 63 = water, 64 to 127 = forest, etc., and map to graphics used for those topo features, rather than to color gradients.




More SiVi info & examples, but will eventually expire:
http://www.java-gaming.org/topics/wip-reel/33731/msg/317526/view.html#msg317526
This post also has a link to an interesting slide show by Ken Perlin.

Since the project is open source, you can also sign up on github (http://github.com/philfrei/SiVi) and poke around the code that way.
19  Discussions / Miscellaneous Topics / Re: Game art for programmers with non-existent budgets on: 2014-07-27 03:18:55
You can use SiVi to make some interesting textures. Either use the app settings to write code to recreate the textures procedurally or export them as pngs and import them as assets. Once in, you could, say, fiddle with their alpha channel and overlay them on other graphics, perhaps. The ColorBar that is used can be something simple like a progression from on solid color to another. Clouds, of course, but also certain waxy crayon-like texturing is also easy to do.
http://www.java-gaming.org/topics/wip-reel/33731/msg/317526/view.html#msg317526
20  Game Development / Newbie & Debugging Questions / Re: Runnable jar doesn't play WAV formats on: 2014-07-25 21:42:40
FYI, just in case you aren't aware of this, there are a lot of issues pertaining to audio formats besides whether something is a WAV or not. I apologize if I am mentioning something you already know, but the posts you gave allow an ambiguous interpretation.

It can be stereo or mono, and the bytes can be in either little-endian or big-endian order. It can be 16, 24, or 32 bits encoding. And concerning frame rates, I think (I could be wrong) that 44100 is the maximum supported by Java, but some DAWs are now working at 48000 or 96000 fps. If any of these parameters are varying between the samples, then the formats could be an issue.

I think I also had some trouble once when I designated the 'compression' option when generating a jar in Eclipse for the resource files. This might make a difference as well, though admittedly WAV files are pretty large if they aren't compressed, and this might make using some sort of compression (at some stage or another) mandatory.
21  Game Development / Newbie & Debugging Questions / Re: Java Metronome | Visual Display Sync Problem on: 2014-07-17 23:33:07
I’m not sure I understand what you mean by the “standard technique of calculating the varying amounts of compensating Sleep”...do you mean calculating the delay by checking the system time and then sleeping for that amount of time, or something else?

It's a way of getting a "fixed time" loop. At the start of the loop, obtain the current nanotime. Do the loop's tasks: the update and render, then check the time again. If the "fixed time" amount has not elapsed yet, calculate and sleep the amount of time required to fill out the interval. Even fancier if you want to code it: if you have previously gone over in terms of processing time for a given frame, a fixed time loop algorithm can be written to "play catch up" by going a bit shorter (if there is time left over this iteration) than the required fixed time amount, until the frame loop is back at the correct time slot.

To a large extent, the timing issues that are discussed on that past thread that you quoted are no longer so important. AFAIK, the new Microsoft OS's use a faster system clock now. At that time, it only updated every 15 or 16 milliseconds. In other words, if you aren't expecting to market to Windows XP users, not to worry.

IMHO, the scheduleAtFixedRate type scheduling is perfectly adequate. Regardless of method, if the update and render takes longer than the scheduled time, you are going to get slippage in the frame rate. I don't see how the distinction "heavy lifting" actually means anything useful in this context. Either the tasks can be done within the designated frame rate or they can't. The wrapper for that code should have little or no influence on the execution speed of the tasks being wrapped.

A little slippage in frame rate may not even matter, as long as you are cleanly updating and reporting the metronome state at the time that the frame executes.

I continue to suspect that you might get more accurate scheduling with the scheduleAtFixedRate use of the util.Timer, versus calculating the variable sleep interval yourself, depending on how the Java engineers have implemented this internally. (I assume they know what they are doing.)

Maybe someone with a different opinion will speak up. Usually we hear something if I make an inaccurate remark. But given my tendency to tl;dr posts, perhaps my controversial statements are just be being overlooked.  Smiley

If you want to, you can also look at the ScheduledThreadPoolExecutor as an upgrade to the util.Timer. This gives you some additional exception handling capabilities (in case the TimeTask throws an unchecked exception). Learning about ExecutorServices and what Brian Goetz ("Java Concurrency in Practice") describes as "exploitable parallelism" is probably overkill. It would certainly be an interesting and very involved side trip! I'm in no position to evaluate the pros and cons.
22  Game Development / Newbie & Debugging Questions / Re: Java Metronome | Visual Display Sync Problem on: 2014-07-17 03:02:50
There's a lot of Java to learn, to do what you wish to do. You seem to me to be making good progress.

When you say "game engine", I think you mean to "game loop". An "engine" implies a whole slew of features that will enable a user to build a game via various templates and tools, not just the visual display loop.

It is my guess that if you have a visual display fps that is fine-grained enough, and supporting code that updates and reports the metronome state as cleanly as possible, that this will suffice. 60 fps is considered a good target for games. (Film is often 24 fps, or they do something like use 72 fps but show each frame 3 times. People don't usually notice synching discrepancies in the theaters, do they?)

Part of the reason I think a lack of precision (relative to that needed to make audio work) for sound/visual coordination is that the brain is biased towards fuzzing together sound and visuals as unified events. I'm not sure how to account for this. Maybe it has to do with the fact that the synching happens "higher up" in the nervous system, at some point where visual and aural systems meet, rather than at the more "mechanical" point of contact in the eye or ear. Or maybe it has something to do with sound travelling slower in air than light, thus lagging by varying amounts depending upon distance, i.e., inherently unreliable beyond a certain degree of precision anyway.

Looping the visual display at fixed time amounts by the standard technique of calculating the varying amounts of compensating Sleep will probably work okay. I think you just have to try it and see. I prefer using a util.Timer, as it is just as accurate (I cite "Killer Game Programming" as evidence) and somewhat simpler to code. There is a scheduling command that actively tries to keep the timer locked on a fixed schedule, making adjustments as best as it can if scheduling tasks run either slow or fast. To me that beats calculating sleep intervals, both in terms of the coding involved, and in the hope that the implementers know what they are doing and are handling this task at a level closer to native code. I could be wrong though and the util.Timer scheduling management could be implemented via higher level code similar to what we would write.

You're not doing a lot of "motion" animation are you? More like there are things blinking on and off, right?

The idea of "time stamping" with the audio frame count will only contribute to the extent that the visual frame loop is super solid. If it is, then you could also count visual frames and work out a calculation as to what audio frame range should be reported within a given visual frame. (Main issue would be figuring out a good "0" reference frame.)

But I don't think visual frames are displayed with as much precision as for playing back sound. You are getting into new territory for me. I've been able to be helpful because I'm a step or two ahead in a few regards, but that is all. There is much about the graphics system that I do not know.
23  Game Development / Newbie & Debugging Questions / Re: Java Metronome | Visual Display Sync Problem on: 2014-07-14 08:52:20
Quote
Currently, I don’t update the visual at a specific frame rate. It loop through and checks the system time to see when the visual needs to change, when it needs to change then it just goes and immediately updates the JLabels. Should I be updating these JLabel at a specific frame rate instead? I’m not doing any animations or anything at this point, but are there still benefits of using a frame rate even in my simple example just using JLabels? If so, then maybe this is part of my problem?

Most screen monitors are set to around 60Hz or maybe a little faster, and most game animation is done at 60 fps as well. There's a diminishing returns aspect of trying to update visuals faster than that, especially when the update out paces the screen refresh. Game animation at 60 fps is considered to be quite decent and should be sufficient for your metronome, it seems to me. It might be possible to get even more precise coordination with the sound but that would be moot since displays update very infrequently in comparison to audio frame rates.

It could very well work to write code to update visually "on demand". I've never tried it on anything with continuous animation. I strongly suspect getting a proper game loop structure going will be sufficient and simpler. Have you written one before?

The simplest game loop coding would be to use a util.Timer. You can put any needed updates and renders in a "TimerTask" and set the TimerTask to loop every 15 millis. The rendering code can branch on the boolean that handles the state of the JLabel, using that to decide what to show. (Most game loops use while loops instead, but if you don't have one to pull as a template from other code you've written, I doubt the trouble to write a first one of that form, from scratch, is justified for the scant amount of visuals or state updating you are doing.)

Handing off information between threads via variables is an important technique. It helps keep objects from getting too enmeshed and codependent, and helps with multi-threading. I think the proper term is "loosely coupled", for this sort of communication. If it works, great! If not, I am thinking of trying a strategy where the audio thread "time stamps" those requests to draw, but uses the audio frame number as the stamp value, not the actual processing moment of the audio. But hopefully you won't have to go there.

Are you familiar with the term "volatile"? Make the state boolean for the JLabel volatile, to help ensure timely and non-blocking communication between the audio and game-loop/visual threads.
24  Game Development / Newbie & Debugging Questions / Re: Libgdx sound lag? [solved] on: 2014-07-14 08:16:46
Congratulations!

Did the same code on the PC run clips with a sample rate of 96000? I didn't know Java on PCs could manage 96000Hz. Is this new to Java? Did you do anything special to allow this? Is there something built into LIBGDX that allows it to do this?
25  Game Development / Newbie & Debugging Questions / Re: Java Metronome | Visual Display Sync Problem on: 2014-07-13 21:27:42
Gulp. That's a lot of code to read.

Are you familiar with Java "listeners"? I think the concept is also known as the "Observer" design pattern.

Try this:

(1) On the audio thread, on the very sample that starts a tone, also flag the label for display. Do nothing more than toggle a boolean (the boolean should be volatile), as we don't want the audio processing thread to block with extraneous activities.

(2) I am assuming that you have a 'game loop' of some sort, for showing visual frames at some fixed rate (e.g., 60 fps is a popular choice for games). In your game loop, consult the boolean and use that to decide whether to display or not.

In effect, the item being displayed is an observer or listener to the audio event, and is "registered" in the audio thread.

Since the visual frames occur at a much slower rate than the audio samples (60 fps versus 44100 fps), an additional layer of lag time will be built in (besides the end stage graphics and audio renderings). Perhaps that will suffice?

I'm curious what results you get, if you try this method. I use it in an app that only has gradual sounds, and it looks fine. There are variably glowing lights that are "listening" to the evolving audio volume envelopes of individually associated synth notes, and the synth is set to have a slowish attack and long decay. Your usage will be a better test of the method.
26  Game Development / Newbie & Debugging Questions / Re: Libgdx sound lag? on: 2014-07-12 10:51:42
You could well be right. Is there a way to profile the program and verify that?
27  Game Development / Newbie & Debugging Questions / Re: Libgdx sound lag? on: 2014-07-11 22:06:45
My first guess is that your Android device has considerably less processing power than your PC, and that this accounts for the difference in performance.

Decoding a compressed file takes much more processing than running a wav. If you are trying to do both at the same time, or even just trying to play more than one ogg at once, that could very well be "too much" for your Android device while still being within the capabilities of your PC. (My old PC, from 2004, starts to bog down even with two compressed files playing at the same time. I assume a newer PC can handle considerably more than that.) I don't know what to suggest beyond either trying to create a less ambitious score, or trying to find some way of using less compression, e.g., decompressing and working from the unpacked file stored in memory (uses a lot of memory, yes).

Another remote possibility is that using some sort of mixer rather than running all the files individually might add some efficiency. But I've only done this using Java on PCs, not on Android. I do not know if, for example, the TinySound library could be wrappered or revised to run on Android, or if doing so would help.

Warning: my lack of experience with Android sound means that I could well be overlooking an Android-specific bug. But my general experience with sound leads me to suspect you are trying to do "too much".
28  Game Development / Newbie & Debugging Questions / Re: Libgdx sound lag? on: 2014-07-10 18:03:19
I'd be interested in seeing the code.

You might find the following article interesting, in terms of understanding basic issues pertaining to Java & Sound. Though, it doesn't specifically go into differences in implementation for Android & Java.

"Real Time Low Latency Audio Processing in Java"
http://quod.lib.umich.edu/cgi/p/pod/dod-idx?c=icmc;idno=bbp2372.2007.131
29  Games Center / WIP games, tools & toy projects / Re: WIP Publication Reel on: 2014-07-03 05:14:03
I managed to spend the last two days working on a new feature for the Simplex Noise Visualization Tool project. The result: it is now possible to use the tool to create simple Z-axis animations of noise textures, and to export them as animated gifs.

Click to Play


The gif export coding was very much helped by this posting from Riven:
http://www.java-gaming.org/topics/generate-animated-gifs/24196/view.html
 and from another example that came from the following Oracle Community post:
https://community.oracle.com/thread/1264385
It is unclear to me who the exact authors were on this second example. The following names are some but probably not all the contributors:  Brian Burkhalter, Geoff Titmus, Andrew Thompson.

In any event, my considerably stripped down version, for making an animated gif from an array of BufferedImages, is viewable as part of the open source SiVi project, which can be seen at http://github.com/philfrei/SiVi

Any interest in joining in and adding more features? The original goal was to make a tool to allow one to figure out, in a hands-on fashion, the parameters needed to make various texture effects using Perlin noise (the "Simplex Noise" flavor, in this case, though the principles would tend to apply to his other noise algorithms as well). But it is starting to accumulate ways to export various graphics, too.

As I said, the animation at this point is only on the Z-axis. It would be nice to add animation to other parameters, such as translation or scaling. Not sure when I'm going to be able to get to it. My next Java-coding priority is to get back to a Tanpura that is in the works.

Here's another gif that I made today, trying to approximate Ken Perlin's animated cloud example from his slide show: http://www.noisemachine.com/talk1

Click to Play


If you look at his, you will notice that I didn't quite manage to match his color mapping, and his animation includes considerable horizontal translation (looks like a wind blowing the clouds to the east). I probably should have given my example a faster frame rate, too.

Here is Ken Perlin's cloud gif, from the above cited slide show:
Click to Play


I'm going to post one more, built from one of the images in the SiVi "Gallery". If it doesn't animate at first, it's because the file is rather large (5MB).
Click to Play


If you wish to play with the tool, you can try the following URL:
http://hexara.com/SimplexVisualizer.html
but I have done nothing in terms of making certificates and such. Running and supporting Applets has become too much of a headache. If you don't want to build via the github project, you can download a jar with today's build from here:
http://hexara.com/SiVi.jar

To use: first select a graphic from the Gallery (menubar: View/Gallery) or build your own image. Then, select the Animator tool from the same View tab of the menubar. A form comes up where parameters are entered.

If you have trouble with setting the parameters and having the controls become enabled, try hitting <Enter> in each field where you have put a number. That is kind of annoying, the need to do this--any advice on how to better handle JTextFields so that <Enter> is not needed? Something has to trigger the intake of the value. Maybe someone could help improve this form. It really could use some help.

Last thing, I'm wondering if I can get credited for this as a 2nd project? Now that we have the WIP including "tools" and "toys" I think this project qualifies.
30  Java Game APIs & Engines / Java Sound & OpenAL / Re: Java Audio Metronome | Timing and Speed Problems on: 2014-07-01 17:41:27
Hi philfrei,

I realize it's a small delay and different software...but I've moved recorded music tracks around between different software and computers before with no shift in the timing. A friend and I used to bounce tracks back and forth between his Mac laptop and my PC desktop (he used Logic and I use Magix Samplitude) and there wasn't any timing drift problems as long as my project's tempo matched his project's tempo (or vice versa). But maybe any difference between them would have been too small to notice with instrument tracks?...it's very easy to tell exactly where the start of my metronome tone begins since everything surrounding it is all zero's, but that wouldn't be the case with instrument tracks.

I just added in a print statement for tickBufferSize and it does come back out to equal exactly 44100. The tempo I tested was 60bpm, which I did to avoid any weird cascading rounding errors as you mentioned just to see if it would stay "spot on".

I love your idea of trying to play a sound file in Java and recording that. I'll record 10 minutes of the metronome within my recording software Samplitude so that its easy to compare the difference between the Java playback version and the original. I'll need to figure out how to load the wave file into my program, because I'd like to use the same SourceDataLine method I'm using for my metronome.

Thanks again for all your help! Smiley

Interesting!

I think it is very likely that if you go back to some of those tracks you swapped, there might indeed be some drift. Ears have to be really good, and circumstances very clear to hear imprecisions when only a few millis are involved. I recall once trying to improvise against a friend's track and having the feeling be slightly uncomfortable, unable to get a sense of being "in the pocket". We took a closer look at the rhythms and found one of the drums offset by 4 millis. Straightening that out did a lot to settle my nerves. But I didn't hear it as a mistake, but rather just experienced some tension that I couldn't really explain. It could also have been an example of me just being nervous, and the fix working as a sort of placebo. But my experience was that the fix did feel more solid. (And yes, non-percussive sounds would be next to impossible to detect as being off at this level.)

I tested the idea of the int cast truncation, as well, and found that the "correct" number of frames was being generated, to the nearest frame. Later on, it occurred to me: what if a proper DAW is even more accurate than the sample rate? In order to handle a plethora of sample rates, maybe the DAWs work at a finer granularity than 44100 fps, and the metronomes naturally are tied to the highest level of precision available in that DAW. (My Cakewalk Sonar also handles 48000 sample rate, so it has to have something that is more precise than 44100 fps, but aren't there 96000 tracks now, as well?)

If a DAW's metronome is more accurate than the 44100 sample rate, then the fraction of the frame that is getting truncated in Java, but is handled in the DAW's metronome could cause some drift that is in the ballpark for what you are getting. Maybe?

I'm not sure how the fractions would be handled in the DAW. Maybe something like a Leap Year, adding or taking away an extra frame every now and then? As far as Java is concerned, there is no way I know of to take nanosecond readings at the precise time the frame is run through the digital-to-analog-converter, and the lack of real-time guarantees means the point when the frame is processed in the while loop could vary considerably!

In any event, your demonstration that the metronome is as or more accurate than other commercial metronomes seems like a good reality check. I wonder how your metronome, when running in Android, will compare.

Last bit of musing: if the DAW's metronome IS more accurate (to fractions of a sample), then a recording made from a DAW would most likely be a tiny bit longer than the calculated number of frames (using the truncation that Java does with the int cast). Perhaps that led to the drift in the plus, instead of minus direction, for that test?

I forgot about that post you dug up. I was contradicting the answer of one of my Java heros, Kay Horstmann! I was also doing a bit of venting. Maybe if you like that answer, and found it helpful, you'll give it a +?

Sometimes I wish I had minored in mathematics and/or sound engineering. I have a friend that is an engineer and used to work for Pro Tools. I'll run the idea of the metronome vs sample rate accuracy issue by him next chance I get.
Pages: [1] 2 3 ... 34
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

TehJavaDev (18 views)
2014-08-28 18:26:30

CopyableCougar4 (26 views)
2014-08-22 19:31:30

atombrot (39 views)
2014-08-19 09:29:53

Tekkerue (36 views)
2014-08-16 06:45:27

Tekkerue (33 views)
2014-08-16 06:22:17

Tekkerue (22 views)
2014-08-16 06:20:21

Tekkerue (33 views)
2014-08-16 06:12:11

Rayexar (70 views)
2014-08-11 02:49:23

BurntPizza (47 views)
2014-08-09 21:09:32

BurntPizza (37 views)
2014-08-08 02:01:56
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!