Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (538)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (600)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  Utils essentials  (Read 14329 times)
0 Members and 1 Guest are viewing this topic.
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Posted 2010-03-22 14:29:30 »

I thought I'd try to get some snowball rolling here.

Rules are simple: Post a single static method "Utils" method that you find useful. Hopefully we'll have tons of methods in here that people can copy and paste to use in their own Utils classes.

These methods can be many things, but they deal with a set of parameters and return a single value.

Keep the name of the method very descriptive, not just "getBla", but "calculateBlaFromSetOfBlahblahs".

I'll start with a couple of methods:

1  
2  
3  
4  
5  
6  
// Linear interpolation, get the value between a and b where t is 0-1.
public static float lerp(float a, float b, float t) {
   if (t < 0)
      return a;
   return a + t * (b - a);
}


1  
2  
3  
4  
// Get the euclidean distance between two points.
public static float euclideanDistance(float x1, float y1, float x2, float y2) {
   return (float) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}


Both of these can probably be optimized, so go ahead and post your optimized version.

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Offline Mr. Gol

Senior Devvie


Medals: 1



« Reply #1 - Posted 2010-03-22 18:04:02 »

Funny thread Smiley

In your example, for t=0 you currently do the full calculation, while you can just return "a".

I'll add a method of my own. It can be used to store application data files in the proper location for the current platform. You could use java.util.prefs, but in some cases you just want a place to store files.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
/**
 * Returns a {@code File} that points to the application data with the
 * specified path. The directory returned will be a subdirectory with
 * the application's name, in the platform-specific location for storing
 * application data. If the subdirectory does not already exist it is
 * created.
 * @param appName The name of the application.
 * @param path Relative path to the requested file.
 * @return A {@code File} object that points to the requested file.
 * @throws IllegalArgumentException if the path is empty or absolute.
 */

public static File getApplicationData(String appName, String path) {

    if (appName.length() == 0) {
        throw new IllegalArgumentException("Invalid application name");
    }
       
    if ((path.length() == 0) || path.startsWith("/")) {
        throw new IllegalArgumentException("Invalid path: " + path);
    }

    File appdir = null;
       
    if (System.getProperty("os.name").startsWith("Windows")) {
        appdir = new File(System.getenv("APPDATA"));
    } else if (System.getProperty("os.name").startsWith("Mac OS X")) {
        // This will also work for non-English versions of Mac OS X
        appdir = new File(System.getenv("HOME") + "/Library/Application Support");
    }
   
    // If auto-detection failed, or if not known, fall back to user home
    if ((appdir == null) || !appdir.exists() || !appdir.isDirectory()) {
        appdir = new File(System.getProperty("user.home"));
        appName = "." + appName;
    }
       
    File dir = new File(appdir, appName);
    if (!dir.exists()) {
        boolean success = dir.mkdir();
        if (!success) {
            throw new IllegalStateException("Cannot create directory: " + dir.getAbsolutePath());
        }
    }
       
    return new File(dir.getAbsolutePath() + "/" + path);
}

Offline Momoko_Fan

Junior Devvie


Medals: 2



« Reply #2 - Posted 2010-03-22 19:05:42 »

If we are talking about interpolation, then I have a few as well Smiley

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
public static final float interpolateHermite(float v0, float v1, float v2, float v3, float v01time, float v12time, float x, float tension, float bias){
       float mu2 = x * x;
       float mu3 = mu2 * x;

       float ts, td, a0, a1, a2, a3;
       
       ts  = (v1 - v0) * (((1f + bias) * (1f - tension)) / 2f);
       ts += (v2 - v1) * (((1f - bias) * (1f - tension)) / 2f);
       
       td  = (v2 - v1) * (((1f + bias) * (1f - tension)) / 2f);
       td += (v3 - v2) * (((1f - bias) * (1f - tension)) / 2f);

       a0  =  2f * mu3 - 3f * mu2 + 1f;
       a1  =       mu3 - 2f * mu2 + x;
       a2  =       mu3 -      mu2;
       a3  = -2f * mu3 + 3f * mu2;

       return a0 * v1
            + a1 * ts
            + a2 * td
            + a3 * v2;
    }


1  
2  
3  
4  
5  
6  
7  
public static final float interpolateCatmullRom(float v0, float v1, float v2, float v3, float x){
        return 0.5f * ((-v0 + 3f*v1 -3f*v2 + v3)*x*x*x
                    +  (2f*v0 -5f*v1 + 4f*v2 - v3)*x*x
                    +  (-v0+v2)*x
                    +  2f*v1);

    }

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
    public static final float interpolateCubic(float v0, float v1, float v2, float v3, float x){
        float p = (v3 - v2) - (v0 - v1);
        float q = (v0 - v1) - p;
        float r = v2 - v0;
        float s = v1;

        return p * x * x * x
             + q * x * x
             + r * x
             + s;
    }

1  
2  
3  
4  
5  
6  
    public static final float interpolateCosine(float v0, float v1, float x){
        float ft = x * (float)Math.PI;
        float f = (1 - (float)Math.cos(ft)) * 0.5f;

        return v0 * (1 - f) + v1 * f;
    }


Some noise
1  
2  
3  
4  
5  
6  
7  
8  
9  
public static final float noise1(int x){
       x = (x << 13) ^ x;
       x = (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff;
       return 1.0f - x / 1073741824.0f;
    }

    public static final float noiseSmooth1(int x){
       return noise1(x) / 2.0f + noise1(x-1) / 4.0f + noise1(x+1) / 4.0f;
    }


Not sure where I got it from, but hopefully there's no copyright on functions lol
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Reply #3 - Posted 2010-03-22 19:59:51 »

Superb! I smell a good thread coming out of this.

Please remember to add a comment describing the function, e.g.:

// This function interpolates ... by taking x1, y1, etc., and returning a processed value...

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Offline pjt33
« Reply #4 - Posted 2010-03-22 21:20:39 »

A generic toString for debugging output with arrays:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
   public static String toString(Object obj)
   {
      if (obj instanceof Object[])
      {
         StringBuilder sb = new StringBuilder();
         sb.append("[");
         boolean first = true;
         for (Object o : (Object[])obj)
         {
            if (first) first = false;
            else sb.append(", ");
            sb.append(toString(o));
         }
         return sb.append("]").toString();
      }
      if (obj instanceof int[]) return Arrays.toString((int[])obj);
      if (obj instanceof long[]) return Arrays.toString((long[])obj);
      if (obj instanceof short[]) return Arrays.toString((short[])obj);
      if (obj instanceof byte[]) return Arrays.toString((byte[])obj);
      if (obj instanceof double[]) return Arrays.toString((double[])obj);
      if (obj instanceof float[]) return Arrays.toString((float[])obj);
      if (obj instanceof boolean[]) return Arrays.toString((boolean[])obj);
      return obj == null ? "null" : obj.toString();
   }
Offline pjt33
« Reply #5 - Posted 2010-03-22 21:23:40 »

A wrapper around Color.HSBtoRGB which works around a bug I reported 7.5 years ago.
1  
2  
3  
4  
5  
6  
7  
   public static int HSBtoRGB(float hue, float saturation, float brightness)
   {
      // Fix for bug 4759386.
      float h = (hue - (float)Math.floor(hue)) * 6f;
      if (h >= 6f) hue = 0f;
      return Color.HSBtoRGB(hue, saturation, brightness);
   }
Offline pjt33
« Reply #6 - Posted 2010-03-22 21:29:05 »

And one more for now: a method I've found very helpful for working out why my OpenGL scene isn't rendering as I think it should:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
   /**
    * Gets a string representing the current lighting state.
    * @param gl The OpenGL handle.
    * @return A string which describes the current lights at a basic level.
    */

   public static String lightingDebugString(GL gl)
   {
      // First thing to check: are we actually doing lighting at all?
      boolean lighting = gl.glIsEnabled(GL.GL_LIGHTING);
      if (!lighting)
      {
         return "Lighting is disabled; glColor controls vertex colours";
      }

      // Ok. We'll assemble stuff.
      StringBuilder sb = new StringBuilder();
      sb.append("Lighting is enabled\n");
      float[] buf = new float[4];

      // Global stuff. There are more parameters, but this is sufficient for
      // now. Maybe this method should have a verbosity parameter?
      gl.glGetFloatv(GL.GL_LIGHT_MODEL_AMBIENT, buf, 0);
      sb.append("\tScene ambient light: ");
      append(sb, buf);
      sb.append("\n");

      // How many lights must we check?
      int[] ibuf = new int[1];
      gl.glGetIntegerv(GL.GL_MAX_LIGHTS, ibuf, 0);
      int numLights = ibuf[0];

      // List info for the enabled lights.
      sb.append("\tEnabled lights:\n");
      int enabledLightCount = 0;
      for (int i = 0; i < numLights; i++)
      {
         // Note that it is always the case that GL_LIGHT_i = GL_LIGHT0 + i:
         // ref. http://www.opengl.org/sdk/docs/man/xhtml/glGetLight.xml
         if (gl.glIsEnabled(GL.GL_LIGHT0 + i))
         {
            enabledLightCount++;
            sb.append("\t\tLight ").append(i).append("\n");

            // Key light parameters. Ignoring things like GL_SPOT_EXPONENT.
            gl.glGetLightfv(GL.GL_LIGHT0 + i, GL.GL_AMBIENT, buf, 0);
            sb.append("\t\t\tAmbient: ");
            append(sb, buf);
            sb.append("\n");

            gl.glGetLightfv(GL.GL_LIGHT0 + i, GL.GL_DIFFUSE, buf, 0);
            sb.append("\t\t\tDiffuse: ");
            append(sb, buf);
            sb.append("\n");

            gl.glGetLightfv(GL.GL_LIGHT0 + i, GL.GL_POSITION, buf, 0);
            sb.append("\t\t\tPosition: ");
            append(sb, buf);
            sb.append("\n");

            sb.append("\t\t\tOther parameters snipped");
         }
      }

      // If no lights enabled, say so.
      if (enabledLightCount == 0)
      {
         sb.append("\t\tNone");
      }

      return sb.toString();
   }

   /**
    * Utility method to append a float[] to a StringBuilder.
    * @param sb The string builder to which to append.
    * @param vals The array to append.
    */

   private static void append(StringBuilder sb, float[] vals)
   {
      sb.append("[");
      for (int i = 0; i < vals.length; i++)
      {
         if (i > 0)
         {
            sb.append(", ");
         }
         sb.append(vals[i]);
      }
      sb.append("]");
   }
Offline Mr. Gol

Senior Devvie


Medals: 1



« Reply #7 - Posted 2010-03-22 22:10:32 »

A wrapper around Color.HSBtoRGB which works around a bug I reported 7.5 years ago.

Edit: Damn, the "evaluation" section isn't even filled in, which probably means that no Sun employee has ever looked into this!  Shocked
Offline i30817

Junior Devvie





« Reply #8 - Posted 2010-03-22 22:18:16 »

http://code.google.com/p/bookjar-utils/source/browse/BookJar-utils/src/util/io/IoUtils.java

http://code.google.com/p/bookjar-utils/source/browse/BookJar-utils/src/util/threads/Threads.java
Offline Gudradain
« Reply #9 - Posted 2010-03-22 22:48:29 »

It's probably already in the JRE but never find it.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
        /**
    * The angle of the vector (x, y). The angle is between 0 and 2*PI.
    * @param x The x value of the vector.
    * @param y The y value of the vector.
    * @return The angle of the vector (x, y).
    */

   public static double findAngle(double x, double y){
      double theta = 0;
      if(x == 0){
         if(y>0){
            theta = Math.PI/2;
         }else if(y < 0){
            theta = Math.PI*3/2;
         }
      }
      if(x > 0){
         theta = Math.atan(y/Math.abs(x));
      }
      if(x < 0){
         theta = Math.PI - Math.atan(y/Math.abs(x));
      }

      if(theta < 0){
         theta += Math.PI*2;
      }
      return theta;
   }

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline jojoh

JGO Knight


Medals: 5
Projects: 7


games4j.com


« Reply #10 - Posted 2010-03-23 00:09:00 »

It's probably already in the JRE but never find it.

Good thread.

I think what you are looking for is: Math.atan2(y, x);
Except for that it is from -PI to PI IIRC.

Offline DzzD
« Reply #11 - Posted 2010-03-23 00:15:56 »

Not sure where I got it from, but hopefully there's no copyright on functions lol
hehe probably from hugo elias website Wink http://freespace.virgin.net/hugo.elias/models/m_perlin.htm (NB : those lack of optimisation are hurting my eyes : /2 => * 0.5 , /constante => *1.0/constante ; unnecessary float cast Sad )


anyway nice thread

Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #12 - Posted 2010-03-23 01:32:33 »

Here's a nice self-contained snippet from Rebirth, to make a shallow copy from one object to an already existing one. Useful for dynamically reloading an object when it's on-disk state changes.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
public static void shallowCopy(Object source, Object dest, final boolean publicOnly)
   {
      if (!source.getClass().isInstance(dest))
         throw new IllegalArgumentException();
     
      Field[] sourceFields = ReflectionUtil.getAllDeclaredFields(source, publicOnly);
      for (int i=0; i<sourceFields.length; i++)
      {
         try
         {
            Field f = sourceFields[i];
           
            final int mods = f.getModifiers();
            if (Modifier.isStatic(mods) || Modifier.isFinal(mods))
               continue;
           
            f.setAccessible(true);
           
            Object sourceValue = f.get(source);
            f.set(dest, sourceValue);
         }
         catch (IllegalArgumentException e)
         {
            e.printStackTrace();
         }
         catch (IllegalAccessException e)
         {
            e.printStackTrace();
         }
      }
   }

   /** 'publicOnly' just gets public fields (Class.getFields vs. Class.getDeclaredFields) so we can work with reduced
    *  functionality in a sandboxed environment (ie. applets)
    */

   public static Field[] getAllDeclaredFields(Object object, final boolean publicOnly)
   {
      ArrayList<Field> result = new ArrayList<Field>();
     
      Class<?> clazz = object.getClass();
      while (clazz != null)
      {
         Field[] fields;
         if (publicOnly)
            fields = clazz.getFields();
         else
            fields = clazz.getDeclaredFields();
         
         for (int i=0; i<fields.length; i++)
            result.add(fields[i]);
         
         clazz = clazz.getSuperclass();
      }
     
      return result.toArray(new Field[result.size()]);
   }


[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 840
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #13 - Posted 2010-03-23 06:47:36 »

Here's a nice self-contained snippet from Rebirth, to make a shallow copy from one object to an already existing one. Useful for dynamically reloading an object when it's on-disk state changes.

1  
2  
3  
4  
5  
6  
7  
8  
9  
...
            f.setAccessible(true);

   /** 'publicOnly' just gets public fields (Class.getFields vs. Class.getDeclaredFields) so we can work with reduced
    *  functionality in a sandboxed environment (ie. applets)
    */

   public static Field[] getAllDeclaredFields(Object object, final boolean publicOnly)
   {
   }



Funny thing that you are coding for unsigned applets, yet Field.setAccessible(true) will always throw a SecurityException, regardless of whether the field is 'already' public.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 840
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #14 - Posted 2010-03-23 06:50:38 »

In your example, for t=0 you currently do the full calculation, while you can just return "a".

You made him change perfectly fast lerp-code, adding a branch that will probably suck all the speed out of it.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Reply #15 - Posted 2010-03-23 08:27:46 »

1  
2  
3  
4  
5  
6  
// Getting position in a quadratic bezier
// Usage: x = quadraticBezier(x1, x2, x3, 0.5f) and y = quadraticBezier(y1,y2,y3,0.5f)
// Returns the x,y point at 0.5 in the curve.
public static float quadraticBezier(float a, float b, float c, float t) {
   return (((1f - t) * (1f - t)) * a) + (((2f * t) * (1f - t)) * b) + ((t * t) * c);
}

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Reply #16 - Posted 2010-03-23 08:40:53 »

These are a set of rotation functions.

They essentially rotate a point around a pivot point given an angle, where angle is in degrees.



1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
   public static float getRotatedX(float currentX, float currentY, float pivotX, float pivotY, float angle) {
      float x = currentX-pivotX;
      float y = currentY-pivotY;
      float a = (float) Math.toRadians(angle);
      float xr = (float) ((x * Math.cos(a)) - (y * Math.sin(a)));
      return xr+pivotX;
   }
   
   public static float getRotatedY(float currentX, float currentY, float pivotX, float pivotY, float angle) {
      float x = currentX-pivotX;
      float y = currentY-pivotY;
      float a = (float) Math.toRadians(angle);
      float yr = (float) ((x * Math.sin(a)) + (y * Math.cos(a)));
      return yr+pivotY;
   }

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #17 - Posted 2010-03-23 10:40:04 »

Funny thing that you are coding for unsigned applets, yet Field.setAccessible(true) will always throw a SecurityException, regardless of whether the field is 'already' public.

Nope. The above code works just fine in an unsigned applet (whereas the previous version, without the 'publicOnly' would throw a security exception).

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Online Roquen
« Reply #18 - Posted 2010-03-23 11:00:17 »

@Appel:

For a base version of lerp, I'd suggest skipping all range checking and allow extrapolation for t outside of [0,1]:

1  
2  
3  
4  
public static float lerp(float a, float b, float t) 
{
  return a + t * (b - a);
}



For performance reasons, usage of Math.pow should be avoided when the exponent is known, esp for small exponents:

1  
2  
3  
4  
5  
6  
7  
public static float euclideanDistance2D(float x1, float y1, float x2, float y2)
{
  float dx = x1-x2;
  float dy = y1-y2;

  return (float)Math.sqrt(dx*dx + dy*dy);
}


It's also worth noting that distance squared is as good a metric as distance, so this can be used in many instances (esp for compares):

1  
2  
3  
4  
5  
6  
7  
public static float euclideanDistanceSq2D(float x1, float y1, float x2, float y2)
{
  float dx = x1-x2;
  float dy = y1-y2;

  return dx*dx + dy*dy;
}


@Momoko_Fan:

All the common Java compiler do not perform common-expression removal, so IMHO it's a good idea to manually perform.

I'd also suggest converting polynomial evaluations into Horner form:

1  
2  
3  
4  
5  
6  
7  
8  
9  
public static final float interpolateCubic(float v0, float v1, float v2, float v3, float x)
{
  float p = (v3 - v2) - (v0 - v1);
  float q = (v0 - v1) - p;
  float r = v2 - v0;
  float s = v1;

  return ((p*x + q)* x + r)*x + s;
}

Offline Mr. Gol

Senior Devvie


Medals: 1



« Reply #19 - Posted 2010-03-23 11:01:50 »

You made him change perfectly fast lerp-code, adding a branch that will probably suck all the speed out of it.

He didn't change it yet. But I assume that this means the currently existing branch for t < 0 is also slowing it down. I'm not even sure why this exists, considering the input is assumed to be between 0 and 1. If it's guarding for invalid input, why isn't there a check for inputs > 1?
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Reply #20 - Posted 2010-03-23 11:08:34 »

No problem Smiley I know my Util methods aren't optimized, it just hasn't bothered me really. I'm already updating my class though.

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Online Roquen
« Reply #21 - Posted 2010-03-23 11:10:45 »


Ken Perlin's 'ease' functions:

For inputs 0 <= t <= 1, returns a smooth value on [0,1].

The first version is first order continuous, the second is continous is all derv.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
public static final float
perlinEase(float t)
{
  return (t*t*(3.f-(t+t)));
}

public static final float
perlinEase2(float t)
{
  float t3 = t*t*t;

  return t3*(10.f+t*(-15.f+6.f*t));
}
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Reply #22 - Posted 2010-03-23 11:23:08 »

Cubic Spline interpolation :

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
   
// Takes in v0 and v3 points with v1 and v2 control points. t is 0-1.
// Returns the interpolated at t.
public static float cubicSplineInterpolate(float v0, float v1, float v2, float v3, float t) {
      float A = v3 - (3f * v2) + (3f * v1) - v0;
      float B = (3f * v2) - (6f * v1) + (3f * v0);
      float C = (3f * v1) - (3f * v0);
      float D = v0;

      float v = (A * (t * t * t)) + (B * (t * t)) + (C * t) + D;

      return v;
   }

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Offline ryanm

Senior Devvie


Projects: 1
Exp: 15 years


Used to be bleb


« Reply #23 - Posted 2010-03-23 12:00:47 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
/**
 * Calculates the mean and concentration of a number of angles
 *
 * @param angles
 *           An array of angles, in radians
 * @return A two-element array { mean, concentration }. The
 *         concentration metric will be 1 if all input angles are
 *         identical and zero of the angles are distributed evenly
 *         around the circle. I doubt it varies linearly though.
 */

public static float[] meanAngle( float[] angles )
{
   double meanX = 0;
   double meanY = 0;

   for( int i = 0; i < angles.length; i++ )
   {
      meanY += Math.sin( angles[ i ] );
      meanX += Math.cos( angles[ i ] );
   }

   meanX /= angles.length;
   meanY /= angles.length;

   float[] results = new float[ 2 ];

   results[ 0 ] = ( float ) Math.atan2( meanY, meanX );
   results[ 1 ] = ( float ) Math.sqrt( meanX * meanX + meanY * meanY );

   return results;
}


Too big to be a snippet, and not my code, but too nice to leave out: Riven's LUT trig methods
Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 840
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #24 - Posted 2010-03-23 15:43:15 »

writing JPG with specified quality, to any Outputstream (not only to a file)

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
   public static void writeJPG(BufferedImage img, final OutputStream out, float quality) throws IOException
   {
      ImageOutputStreamImpl output = new ImageOutputStreamImpl()
      {
         @Override
         public int read(byte[] b, int off, int len) throws IOException
         {
            throw new UnsupportedOperationException();
         }

         @Override
         public int read() throws IOException
         {
            throw new UnsupportedOperationException();
         }

         @Override
         public void write(byte[] buf, int off, int len) throws IOException
         {
            out.write(buf, off, len);
         }

         @Override
         public void write(int b) throws IOException
         {
            out.write(b);
         }

         @Override
         public void flush() throws IOException
         {
            super.flush();

            out.flush();
         }

         @Override
         public void close() throws IOException
         {
            super.close();

            out.close();
         }
      };

      Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
      ImageWriter writer = iter.next();
      ImageWriteParam iwp = writer.getDefaultWriteParam();
      iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      iwp.setCompressionQuality(quality);

      writer.setOutput(out);
      IIOImage image = new IIOImage(img, null, null);
      writer.write(null, image, iwp);
      writer.dispose();
      output.close();
   }



Nope. The above code works just fine in an unsigned applet (whereas the previous version, without the 'publicOnly' would throw a security exception).
Sorry, was confused with field.setAccessible(true) on a publicly accessible field persecutioncomplex

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline woogley
« Reply #25 - Posted 2010-03-23 16:14:32 »

@Riven

Didn't you create a method (for your signature trickery) that writes an Image[] to an animated GIF? Any chance that's published somewhere?
Offline Riven
« League of Dukes »

« JGO Overlord »


Medals: 840
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #26 - Posted 2010-03-23 17:20:24 »

http://riven8192.blogspot.com/2010/02/image-java-animated-gifs.html

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Reply #27 - Posted 2010-03-23 18:22:53 »

This is a method I just restructured. I ran a few test cases on it, and it seems to work. (No guarantees though, as I've often thought I finally cracked the solution to this but after a while it seems to fail, but pretty sure now  Grin)

I've sometimes gone mad trying to figure out... into what direction I should interpolate a rotation, given a object facing angleFrom but needs to face a new angleTo.

Example, a defense-tower in a game that has acquired a new target and must look at it. You don't want it to rotate a 350° clockwise if it could have rotated 10° counter-clockwise!

With this method you can determine the rotation direction.

false = rotate clockwise
true = rotate counter-clockwise

1  
2  
3  
4  
public static boolean shouldRotateCounterClockwise(float angleFrom, float angleTo) {
   float diff = (angleFrom - angleTo) % 360;
   return diff > 0 ? diff < 180 : diff < -180;
}

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Online Roquen
« Reply #28 - Posted 2010-03-23 18:35:34 »

Maybe my brain is not in gear, but doesn't the following work:

1  
2  
3  
4  
5  
6  
  float diff = (angleFrom-angleTo) % 360;

  if (diff > 0) return diff<180;  
 
  return diff < -180;
 
Offline appel

JGO Wizard


Medals: 68
Projects: 4


I always win!


« Reply #29 - Posted 2010-03-23 19:01:53 »

Maybe my brain is not in gear, but doesn't the following work:

Thanks. I've updated my function, and made my own adjustments as well Cheesy

Check out the 4K competition @ www.java4k.com
Check out GAMADU (my own site) @ http://gamadu.com/
Pages: [1] 2
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

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

The first screenshot will be displayed as a thumbnail.

rwatson462 (28 views)
2014-12-15 09:26:44

Mr.CodeIt (19 views)
2014-12-14 19:50:38

BurntPizza (39 views)
2014-12-09 22:41:13

BurntPizza (74 views)
2014-12-08 04:46:31

JscottyBieshaar (36 views)
2014-12-05 12:39:02

SHC (49 views)
2014-12-03 16:27:13

CopyableCougar4 (44 views)
2014-11-29 21:32:03

toopeicgaming1999 (112 views)
2014-11-26 15:22:04

toopeicgaming1999 (98 views)
2014-11-26 15:20:36

toopeicgaming1999 (29 views)
2014-11-26 15:20:08
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

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
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!