changed Vector2D to Vector2f insted and added sound but the sound is not finnishd yet.

and added a update method to entity for ex the sound entity to update its position in the 
world. Added loging support to whit MultiPrintStream.java
This commit is contained in:
Ziver Koc 2007-03-15 19:52:28 +00:00
parent b2cf5d543b
commit 9d4810d38e
37 changed files with 1262 additions and 39 deletions

View file

@ -0,0 +1,53 @@
package ei.engine.sound;
import java.io.IOException;
import org.lwjgl.openal.AL10;
import ei.engine.scene.Entity;
import ei.engine.util.MultiPrintStream;
/**
* A sound that can be played through OpenAL
*
* @author Kevin Glass
*/
public class Sound extends Entity{
/** The buffer containing the sound */
private int buffer;
/**
* Create a new sound
*
* @param name The name of the sound
* @param ref the path to the sound file
*/
public Sound(String name, String ref) {
super(name);
try {
this.buffer = SoundLoader.getInstnace().loadSound(ref);
} catch (IOException e) {
MultiPrintStream.out.println("Unable to load sound: "+ref+" - "+e.getMessage());
e.printStackTrace();
}
}
/**
* Play this sound as a sound effect
*
* @param pitch The pitch of the play back
* @param gain The gain of the play back
*/
public void play(float pitch, float gain) {
SoundLoader.getInstnace().playSound(buffer, pitch, gain, getLocation());
}
public void update() {
//AL10.alSource(source.get(0), AL10.AL_POSITION, sourcePos);
}
/**
* unimplamented method
*/
public void render() {}
}

View file

@ -0,0 +1,200 @@
package ei.engine.sound;
import java.io.IOException;
import java.io.InputStream;
import java.nio.IntBuffer;
import java.util.HashMap;
import org.lwjgl.BufferUtils;
import org.lwjgl.Sys;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10;
import org.lwjgl.util.WaveData;
import ei.engine.math.Vector2f;
import ei.engine.sound.decoders.OggData;
import ei.engine.sound.decoders.OggDecoder;
import ei.engine.util.MultiPrintStream;
/**
* Responsible for holding and playing the sounds used in the game.
*
* @author Kevin Glass
* @author Ziver Koc
*/
public class SoundLoader {
/** The single instance of this class */
private static SoundLoader instance = new SoundLoader();
/** True if sound effects are turned on */
private boolean soundsEnabled;
/** The number of sound sources enabled - default 8 */
private int sourceCount;
/** The map of references to IDs of previously loaded sounds */
private HashMap<String, Integer> loaded = new HashMap<String, Integer>();
/** The OpenGL AL sound sources in use */
private IntBuffer sources;
/** The next source to be used for sound effects */
private int nextSource;
/**
* Create a new sound store
*/
private SoundLoader() {
init();
}
/**
* Indicate whether sound effects should be played
*
* @param sounds True if sound effects should be played
*/
public void setEnabled(boolean enabled) {
this.soundsEnabled = enabled;
}
/**
* Check if sound effects are currently enabled
*
* @return True if sound effects are currently enabled
*/
public boolean isEnabled() {
return soundsEnabled;
}
/**
* Initialise the sound effects stored. This must be called
* before anything else will work
*/
private void init() {
try {
AL.create();
soundsEnabled = true;
} catch (Exception e) {
e.printStackTrace();
soundsEnabled = false;
}
if (soundsEnabled) {
sourceCount = 8;
sources = BufferUtils.createIntBuffer(sourceCount);
AL10.alGenSources(sources);
if (AL10.alGetError() != AL10.AL_NO_ERROR) {
soundsEnabled = false;
}
}
}
/**
* Play the specified buffer as a sound effect with the specified
* pitch and gain.
*
* @param buffer The ID of the buffer to play
* @param pitch The pitch to play at
* @param gain The gain to play at
*/
void playSound(int buffer,float pitch,float gain, Vector2f pos) {
if (soundsEnabled) {
nextSource++;
if (nextSource >= sourceCount) {
nextSource = 1;
}
AL10.alSourceStop(sources.get(nextSource));
AL10.alSourcei(sources.get(nextSource), AL10.AL_BUFFER, buffer);
AL10.alSourcef(sources.get(nextSource), AL10.AL_PITCH, pitch);
AL10.alSourcef(sources.get(nextSource), AL10.AL_GAIN, gain);
//specify where the sound is comming from by tree axes x,y and z
AL10.alSource3f(sources.get(nextSource), AL10.AL_POSITION,
pos.getX(), pos.getY(), 0);
//AL10.alSource(sources.get(nextSource), AL10.AL_VELOCITY, sourceVel);
//AL10.alSourcei(sources.get(nextSource), AL10.AL_LOOPING, AL10.AL_TRUE );
AL10.alSourcePlay(sources.get(nextSource));
}
}
/**
* Get the Sound based on a specified file path in the classpath
*
* @param ref The reference to the file in the classpath
* @return An integer value that represents the buffer -1 if sound is disabled
* @throws IOException Indicates a failure to load the sound file
*/
public int loadSound(String ref) throws IOException {
if (!soundsEnabled) {
return -1;
}
int buffer = -1;
if (loaded.get(ref) != null) {
buffer = ((Integer) loaded.get(ref)).intValue();
}
else {
MultiPrintStream.out.println("Loading: "+ref);
try {
IntBuffer buf = BufferUtils.createIntBuffer(1);
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(ref);
String extension = getFileExtension(ref);
AL10.alGenBuffers(buf);
if(extension.equals("ogg")){
OggDecoder decoder = new OggDecoder();
OggData ogg = decoder.getData(in);
AL10.alBufferData(buf.get(0), ogg.channels > 1 ? AL10.AL_FORMAT_STEREO16 : AL10.AL_FORMAT_MONO16, ogg.data, ogg.rate);
}
else if(extension.equals("wav")){
//
WaveData wav = WaveData.create(in);
AL10.alBufferData(buf.get(0), wav.format, wav.data, wav.samplerate);
wav.dispose();
}
else{
MultiPrintStream.out.println("Unknown file format: "+ref);
return -1;
}
loaded.put(ref,new Integer(buf.get(0)));
buffer = buf.get(0);
} catch (Exception e) {
e.printStackTrace();
Sys.alert("Error","Failed to load: "+ref+" - "+e.getMessage());
MultiPrintStream.out.println("Failed to load: "+ref+" - "+e.getMessage());
soundsEnabled = false;
return -1;
//System.exit(0);
}
}
if (buffer == -1) {
throw new IOException("Unable to load: "+ref);
}
return buffer;
}
private String getFileExtension(String file){
int dotPlace = file.lastIndexOf ( '.' );
if ( dotPlace >= 0 ){
return file.substring(dotPlace + 1, file.length());
}
else{
return "";
}
}
/**
* Get the single instance of this class
*
* @return The single instnace of this class
*/
public static SoundLoader getInstnace() {
if(instance == null){
instance = new SoundLoader();
}
return instance;
}
}

View file

@ -0,0 +1,17 @@
package ei.engine.sound.decoders;
import java.nio.ByteBuffer;
/**
* Data describing the sounds in a OGG file
*
* @author Kevin Glass
*/
public class OggData {
/** The data that has been read from the OGG file */
public ByteBuffer data;
/** The sampling rate */
public int rate;
/** The number of channels in the sound file */
public int channels;
}

View file

@ -0,0 +1,329 @@
package ei.engine.sound.decoders;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.jcraft.jogg.Packet;
import com.jcraft.jogg.Page;
import com.jcraft.jogg.StreamState;
import com.jcraft.jogg.SyncState;
import com.jcraft.jorbis.Block;
import com.jcraft.jorbis.Comment;
import com.jcraft.jorbis.DspState;
import com.jcraft.jorbis.Info;
import ei.engine.util.MultiPrintStream;
/**
* Decode an OGG file to PCM data
*
* @author Kevin Glass
*/
public class OggDecoder {
/** The conversion buffer size */
private int convsize = 4096 * 4;
/** The buffer used to read OGG file */
private byte[] convbuffer = new byte[convsize]; // take 8k out of the data segment, not the stack
/**
* Create a new OGG decoder
*/
public OggDecoder() {
}
/**
* Get the data out of an OGG file
*
* @param input The input stream from which to read the OGG file
* @return The data describing the OGG thats been read
*/
public OggData getData(InputStream input) {
ByteArrayOutputStream dataout = new ByteArrayOutputStream();
SyncState oy = new SyncState(); // sync and verify incoming physical bitstream
StreamState os = new StreamState(); // take physical pages, weld into a logical stream of packets
Page og = new Page(); // one Ogg bitstream page. Vorbis packets are inside
Packet op = new Packet(); // one raw packet of data for decode
Info vi = new Info(); // struct that stores all the static vorbis bitstream settings
Comment vc = new Comment(); // struct that stores all the bitstream user comments
DspState vd = new DspState(); // central working state for the packet->PCM decoder
Block vb = new Block(vd); // local working space for packet->PCM decode
byte[] buffer;
int bytes = 0;
boolean bigEndian = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN);
// Decode setup
oy.init(); // Now we can read pages
while (true) { // we repeat if the bitstream is chained
int eos = 0;
// grab some data at the head of the stream. We want the first page
// (which is guaranteed to be small and only contain the Vorbis
// stream initial header) We need the first page to get the stream
// serialno.
// submit a 4k block to libvorbis' Ogg layer
int index = oy.buffer(4096);
buffer = oy.data;
try {
bytes = input.read(buffer, index, 4096);
} catch (Exception e) {
MultiPrintStream.out.println("Failure reading in vorbis");
MultiPrintStream.out.println(e);
System.exit(0);
}
oy.wrote(bytes);
// Get the first page.
if (oy.pageout(og) != 1) {
// have we simply run out of data? If so, we're done.
if (bytes < 4096)
break;
// error case. Must not be Vorbis data
MultiPrintStream.out.println("Input does not appear to be an Ogg bitstream.");
System.exit(0);
}
// Get the serial number and set up the rest of decode.
// serialno first; use it to set up a logical stream
os.init(og.serialno());
// extract the initial header from the first page and verify that the
// Ogg bitstream is in fact Vorbis data
// I handle the initial header first instead of just having the code
// read all three Vorbis headers at once because reading the initial
// header is an easy way to identify a Vorbis bitstream and it's
// useful to see that functionality seperated out.
vi.init();
vc.init();
if (os.pagein(og) < 0) {
// error; stream version mismatch perhaps
MultiPrintStream.out.println("Error reading first page of Ogg bitstream data.");
System.exit(0);
}
if (os.packetout(op) != 1) {
// no page? must not be vorbis
MultiPrintStream.out.println("Error reading initial header packet.");
System.exit(0);
}
if (vi.synthesis_headerin(vc, op) < 0) {
// error case; not a vorbis header
MultiPrintStream.out.println("This Ogg bitstream does not contain Vorbis audio data.");
System.exit(0);
}
// At this point, we're sure we're Vorbis. We've set up the logical
// (Ogg) bitstream decoder. Get the comment and codebook headers and
// set up the Vorbis decoder
// The next two packets in order are the comment and codebook headers.
// They're likely large and may span multiple pages. Thus we reead
// and submit data until we get our two pacakets, watching that no
// pages are missing. If a page is missing, error out; losing a
// header page is the only place where missing data is fatal. */
int i = 0;
while (i < 2) {
while (i < 2) {
int result = oy.pageout(og);
if (result == 0)
break; // Need more data
// Don't complain about missing or corrupt data yet. We'll
// catch it at the packet output phase
if (result == 1) {
os.pagein(og); // we can ignore any errors here
// as they'll also become apparent
// at packetout
while (i < 2) {
result = os.packetout(op);
if (result == 0)
break;
if (result == -1) {
// Uh oh; data at some point was corrupted or missing!
// We can't tolerate that in a header. Die.
MultiPrintStream.out.println("Corrupt secondary header. Exiting.");
System.exit(0);
}
vi.synthesis_headerin(vc, op);
i++;
}
}
}
// no harm in not checking before adding more
index = oy.buffer(4096);
buffer = oy.data;
try {
bytes = input.read(buffer, index, 4096);
} catch (Exception e) {
MultiPrintStream.out.println("Failed to read Vorbis: ");
MultiPrintStream.out.println(e);
System.exit(0);
}
if (bytes == 0 && i < 2) {
MultiPrintStream.out.println("End of file before finding all Vorbis headers!");
System.exit(0);
}
oy.wrote(bytes);
}
// Throw the comments plus a few lines about the bitstream we're
// decoding
{
MultiPrintStream.out.println("Bitstream is " + vi.channels + " channel, " + vi.rate + "Hz");
MultiPrintStream.out.println("Encoded by: "+ new String(vc.vendor, 0, vc.vendor.length - 1));
}
convsize = 4096 / vi.channels;
// OK, got and parsed all three headers. Initialize the Vorbis
// packet->PCM decoder.
vd.synthesis_init(vi); // central decode state
vb.init(vd); // local state for most of the decode
// so multiple block decodes can
// proceed in parallel. We could init
// multiple vorbis_block structures
// for vd here
float[][][] _pcm = new float[1][][];
int[] _index = new int[vi.channels];
// The rest is just a straight decode loop until end of stream
while (eos == 0) {
while (eos == 0) {
int result = oy.pageout(og);
if (result == 0)
break; // need more data
if (result == -1) { // missing or corrupt data at this page position
MultiPrintStream.out.println("Corrupt or missing data in bitstream; continuing...");
} else {
os.pagein(og); // can safely ignore errors at
// this point
while (true) {
result = os.packetout(op);
if (result == 0)
break; // need more data
if (result == -1) { // missing or corrupt data at this page position
// no reason to complain; already complained above
} else {
// we have a packet. Decode it
int samples;
if (vb.synthesis(op) == 0) { // test for success!
vd.synthesis_blockin(vb);
}
// **pcm is a multichannel float vector. In stereo, for
// example, pcm[0] is left, and pcm[1] is right. samples is
// the size of each channel. Convert the float values
// (-1.<=range<=1.) to whatever PCM format and write it out
while ((samples = vd.synthesis_pcmout(_pcm,
_index)) > 0) {
float[][] pcm = _pcm[0];
int bout = (samples < convsize ? samples
: convsize);
// convert floats to 16 bit signed ints (host order) and
// interleave
for (i = 0; i < vi.channels; i++) {
int ptr = i * 2;
//int ptr=i;
int mono = _index[i];
for (int j = 0; j < bout; j++) {
int val = (int) (pcm[i][mono + j] * 32767.);
// short val=(short)(pcm[i][mono+j]*32767.);
// int val=(int)Math.round(pcm[i][mono+j]*32767.);
// might as well guard against clipping
if (val > 32767) {
val = 32767;
}
if (val < -32768) {
val = -32768;
}
if (val < 0)
val = val | 0x8000;
if (bigEndian) {
convbuffer[ptr] = (byte) (val >>> 8);
convbuffer[ptr + 1] = (byte) (val);
} else {
convbuffer[ptr] = (byte) (val);
convbuffer[ptr + 1] = (byte) (val >>> 8);
}
ptr += 2 * (vi.channels);
}
}
dataout.write(convbuffer, 0, 2 * vi.channels * bout);
vd.synthesis_read(bout); // tell libvorbis how
// many samples we
// actually consumed
}
}
}
if (og.eos() != 0)
eos = 1;
}
}
if (eos == 0) {
index = oy.buffer(4096);
if (index >= 0) {
buffer = oy.data;
try {
bytes = input.read(buffer, index, 4096);
} catch (Exception e) {
MultiPrintStream.out.println("Failure during vorbis decoding");
MultiPrintStream.out.println(e);
System.exit(0);
}
} else {
bytes = 0;
}
oy.wrote(bytes);
if (bytes == 0)
eos = 1;
}
}
// clean up this logical bitstream; before exit we see if we're
// followed by another [chained]
os.clear();
// ogg_page and ogg_packet structs always point to storage in
// libvorbis. They're never freed or manipulated directly
vb.clear();
vd.clear();
vi.clear(); // must be called last
}
// OK, clean up the framer
oy.clear();
OggData ogg = new OggData();
ogg.channels = vi.channels;
ogg.rate = vi.rate;
byte[] data = dataout.toByteArray();
ogg.data = ByteBuffer.allocateDirect(data.length);
ogg.data.put(data);
ogg.data.rewind();
return ogg;
}
}