Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (494)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
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
1  Game Development / Newbie & Debugging Questions / Re: Algorithm to loop through the color spectrum? on: 2011-12-06 06:38:04
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  
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author David
 */

public class DrawPaletteShiz {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) throws Throwable {
      JFrame jf = new JFrame("Frame");
      final Dimension size = new Dimension(100,100);
      JPanel jp = new JPanel() {

         @Override
         public void paint(Graphics g) {
            float f = new Random().nextFloat();
            for (int i = 0; i < size.width; i++) {
               for (int j = 0; j < size.height; j++) {
                  g.setColor(Color.getHSBColor(f, 1.0f-(float)i/size.width, 1.0f-(float)j/size.height));
                  g.drawLine(i,j,i,j);
               }
            }
            for (int i = 0; i < size.height; i++) {
               g.setColor(Color.getHSBColor((float)i/size.height,1.0f,1.0f));
               g.drawLine(100,i,130,i);
            }
         }

      };
      jf.setResizable(false);
      jp.setPreferredSize(new Dimension(size.width+30,size.height));
      jf.getContentPane().add(jp);
      jf.pack();
      jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jf.show();
      while (true) {
         jp.repaint();
         Thread.sleep(10);
      }
    }

}


have fun brah
2  Game Development / Performance Tuning / Re: WeakHashMap, canonical cache and value recycling? on: 2011-08-16 15:16:31
well then you could just override hashCode and use this

1  
2  
3  
4  
5  
6  
7  
public int hashCode() {
 K key = get();
 if (key == null) {
  return 0;
 }
 return key.hashCode();
}


put:

1  
2  
3  
4  
public void put(K key, V value) {
KeyValuePair kvp = new KeyValuePair(key, value);
       M.put(kvp, kvp);
   }


full:

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  
class WeakHashMap<K, V> {
    ReferenceQueue<KeyValuePair> Q = new ReferenceQueue();
    HashMap<K, KeyValuePair<K,V>> M = new HashMap();
    class KeyValuePair<K, V> extends WeakReference<K, V> {
        V value;
         
        KeyValuePair(K key, V value) {
            super(key, Q);
            this.value = value;
        }
     
      @Override
      public int hashCode() {
         K key = get();
         if (key == null) {
            return 0;
         }
         return key.hashCode();
      }
    }
     
    public void put(K key, V value) {
      KeyValuePair kvp = new KeyValuePair(K, V);
        M.put(kvp, kvp);
    }
     
    public V get(K key) {
        KeyValuePair KVP = M.get(key);
        if (KVP != null) {
         return KVP.value;
        }
        return null;
    }
     
    public void recycle() {
        while (true) {
            KeyValuePair KVP = Q.poll();
            if (KVP != null) {
                V value = KVP.value;
                // do something with value
           }
        }
    }
     
    // etc..
   
}
3  Game Development / Performance Tuning / Re: WeakHashMap, canonical cache and value recycling? on: 2011-08-16 13:31:14
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  
class WeakHashMap<K, V> {
   ReferenceQueue<KeyValuePair> Q = new ReferenceQueue();
   HashMap<K, KeyValuePair<K,V>> M = new HashMap();
   class KeyValuePair<K, V> extends WeakReference<K, V> {
      V value;
     
      KeyValuePair(K key, V value) {
         super(K, value);
         this.value = value;
      }
   }
   
   public void put(K key, V value) {
      M.put(key, new KeyValuePair(K, V));
   }
   
   public V get(K key) {
      KeyValuePair KVP = M.get(key);
      if (KVP != null) {
       return KVP.value;
      }
      return null;
   }
   
   public void recycle() {
      while (true) {
         KeyValuePair KVP = Q.poll();
         if (KVP != null) {
            V value = KVP.value;
            // do something with value
        }
      }
   }
   
   // etc..
 
}


HTH

- David


Thanks, David, but isn't that storing the value as a weak reference and not the key?  I need the same semantics as WeakHashMap, with the key being wrapped in a weak reference.  

The key is the weak reference, look at the KVP constructor

Btw typo:

1  
super(K, value);


should be

1  
super(key, Q);
4  Game Development / Performance Tuning / Re: WeakHashMap, canonical cache and value recycling? on: 2011-08-16 12:59:45
Thanks both for your replies.
Use a ReferenceQueue when adding keys/values to the map
Do you mean basically reimplement WeakHashMap, which I'm happy to do but am hoping not to have to, or just wrapping the keys in a second weak reference?  I'm pretty sure the second wouldn't work because by the time I try and get the value out of the map it'll already be nulled.

I don't understand your example - aren't you calling map.put() with a single argument?

WeakHashMap is very unlikely to be a good choice. Its non-strongly-referenced references will be cleared on every GC (in Suns/Oracles JVM), as opposed to only during a full GC, which you probably want. It can easily run a couple of times per second, which kinda invalidates it as a cache.

What you probably need is a SoftHashMap, which (annoyingly) is not in the standard API. Pick a 3rd party one.

I could have put bets on someone saying this!  Grin

No, I want a WeakHashMap!  I understand it's not much use as a cache in itself, though neither usually would a SoftHashMap be - you want a map to soft referenced values.  In fact, I have a slight feeling of deja vu - I'm pretty sure we've had that conversation in another thread.  Smiley

There's a good article here on this http://www.codeinstructions.com/2008/09/weakhashmap-is-not-cache-understanding.html

So why do I want a WeakHashMap?  Quote from same article on "What is the WeakHashMap good for?"

Quote
If the WeakHashMap is no good for caching, then what is it good for? It is good to implement canonical maps. Lets say you want to associate some extra information to an object that you have a strong reference to. You put an entry in a WeakHashMap with the object as the key, and the extra information as the map value. Then, as long as you keep a strong reference to the object, you will be able to check the map to retrieve the extra information. And once you release the object, the map entry will be cleared and the memory used by the extra information will be released.

This is basically what I'm trying to do - associate a cached object (most likely soft referenced) with a particular object - should have been clearer earlier!  I want the keys to be GC'd as soon as possible, because once the key is unreferenced, the value is unreachable.  The problem is, I want to get the values added to a queue on clearing the key so that I can do other things with them, rather than just having them set to null.

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  
class WeakHashMap<K, V> {
   ReferenceQueue<KeyValuePair> Q = new ReferenceQueue();
   HashMap<K, KeyValuePair<K,V>> M = new HashMap();
   class KeyValuePair<K, V> extends WeakReference<K, V> {
      V value;
     
      KeyValuePair(K key, V value) {
         super(K, Q);
         this.value = value;
      }
   }
   
   public void put(K key, V value) {
      M.put(key, new KeyValuePair(K, V));
   }
   
   public V get(K key) {
      KeyValuePair KVP = M.get(key);
      if (KVP != null) {
       return KVP.value;
      }
      return null;
   }
   
   public void recycle() {
      while (true) {
         KeyValuePair KVP = Q.poll();
         if (KVP != null) {
            V value = KVP.value;
            // do something with value
        }
      }
   }
   
   // etc..
 
}


HTH

- David
5  Game Development / Performance Tuning / Re: WeakHashMap, canonical cache and value recycling? on: 2011-08-16 11:26:40
Use a ReferenceQueue when adding keys/values to the map

example:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
ReferenceQueue<MyData> mQueue = new ReferenceQueue<MyData>();
Map<String, MyData> map = new HashMap();

class MyData extends SoftReference/WeakReference {
  YourKey key;
  MyData(Referent r, YourKey key) {
   super(r, mQueue);
   this.key = key;
  }
}

to add to cache

void put(YourKey key, Referent r) {
  map.put(new MyData(r, key));
}

then to read the recycled objects

while (true) {
 MyData data = mQueue.poll();
 if (data == null) break;
 ...process here
}


HTH

- David
6  Game Development / Newbie & Debugging Questions / Re: List<List<List<Object>>> or List[][] on: 2011-08-08 12:53:18
Thanks for your replies! It made me rethink how I should do this. I have some questions to the code Dx4 and counterp provided.

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  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
public class TileHashtable {

   public class Entry {
      Entry next;
      int x;
      int y;
      int hash;
      UserLayer.Tile value;

      public Entry(Entry next, int x, int y, int hash, Tile value) {
         this.next = next;
         this.x = x;
         this.y = y;
         this.hash = hash;
         this.value = value;
      }

      int hash() {
         return (x << 5) + y;
      }

      public int getHash() {
         return hash;
      }

      public Entry getNext() {
         return next;
      }

      public Tile getValue() {
         return value;
      }

      public int getX() {
         return x;
      }

      public int getY() {
         return y;
      }
   }
   
   int size;
   Entry [] table;

   public TileHashtable() {
      table = new Entry[64];
   }

    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
       // constant multiples at each bit position have a bounded
       // number of collisions (approximately 8 at default load factor).
       h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

   static int getPointHash(int x, int y) {
      return hash((x & 0xFFFF) << 16) | (y & 0xFFFF);
   }

    static int indexFor(int h, int length) {
        return h & (length-1);
    }

   public void clear() {
      for (int i = 0; i < table.length; i++) {
         table[i] = null;
      }
      size = 0;
   }

   public UserLayer.Tile lookup(int x, int y, boolean createIfNotExist) {
      int hash = getPointHash(x, y);
      Entry e;
      int index = indexFor(hash, table.length);
      for (e = table[index]; e != null; e = e.next) {
         if (e.hash == hash && e.x == x && e.y == y) {
            return e.value;
         }
      }

      if (createIfNotExist) {
         UserLayer.Tile val = new UserLayer.Tile();
         table[index] = new Entry(table[index], x, y, hash, val);

         size++;
         return val;
      }

      return null;

   }

   public int size() {
      return size;
   }

   public boolean isEmpty() {
      return size == 0;
   }

   public Iterator<Entry> entryIterator() {
      return new EntryIterator();
   }

   public Iterator<UserLayer.Tile> valueIterator() {
      return new ValueIterator();
   }

   public Iterator<Void> keyIterator() {
      return new KeyIterator();
   }

    private abstract class HashIterator<E> implements Iterator<E> {
        Entry next;   // next entry to return
       int index;      // current slot
       Entry current;   // current entry

        HashIterator() {
            if (size > 0) { // advance to first entry
               Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry nextEntry() {
            Entry e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
       current = e;
            return e;
        }

        public void remove() {
         throw new UnsupportedOperationException("My Dick");
        }

    }

    private final class ValueIterator extends HashIterator<UserLayer.Tile> {
        public UserLayer.Tile next() {
            return nextEntry().value;
        }
    }

    private final class KeyIterator extends HashIterator<Void> {
        public void next(Point p) {

        }

      public Void next() {
         throw new UnsupportedOperationException("My Dick");
      }
    }

    private final class EntryIterator extends HashIterator<Entry> {
        public Entry next() {
            return nextEntry();
        }
    }


}


1  
2  
3  
static int getPointHash(int x, int y) {
      return hash((x & 0xFFFF) << 16) | (y & 0xFFFF);
   }

Why is it that we have to do that AND operation on 0xFFF? To me, it looks like it will return the same, if we exclude that. Also, I don't see a change if I exchange the OR operation with a "+". Can you please explain this?

This is only required if you need to make sure x and y dont exceed a short max.

1  
2  
3  
4  
5  
6  
7  
static int hash(int h) {
        // This function ensures that hashCodes that differ only by
       // constant multiples at each bit position have a bounded
       // number of collisions (approximately 8 at default load factor).
       h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

This also I can't seem to get much meaning out of. I'm unsure what this ensures, and I'd very much like a more in-depth explanation that the comment provided  Clueless

basically this just mixes up the bits of a hashcode, as some hashcodes only differ in bits in lower bits, this function will ensure the bits become more spread from upper->lower

1  
2  
3  
int hash() {
         return (x << 5) + y;
      }

This again makes me feel like I don't really know what the hashes do. I though we'd use the last 16 bits to define y, and the first 16 ones to define x. Also, what happended to the AND-operation with the 0xFFFF byte?

this hash function doesnt really matter, you could make it anything that involves x and y, it would work the same.
7  Game Development / Newbie & Debugging Questions / Re: List<List<List<Object>>> or List[][] on: 2011-08-07 13:29:52
Here's a solution that will be faster than the one provided by counterp but uses the same semantics (there is no unboxing/boxing each read)

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  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
public class TileHashtable {

   public class Entry {
      Entry next;
      int x;
      int y;
      int hash;
      UserLayer.Tile value;

      public Entry(Entry next, int x, int y, int hash, Tile value) {
         this.next = next;
         this.x = x;
         this.y = y;
         this.hash = hash;
         this.value = value;
      }

      int hash() {
         return (x << 5) + y;
      }

      public int getHash() {
         return hash;
      }

      public Entry getNext() {
         return next;
      }

      public Tile getValue() {
         return value;
      }

      public int getX() {
         return x;
      }

      public int getY() {
         return y;
      }
   }
   
   int size;
   Entry [] table;

   public TileHashtable() {
      table = new Entry[64];
   }

    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
       // constant multiples at each bit position have a bounded
       // number of collisions (approximately 8 at default load factor).
       h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

   static int getPointHash(int x, int y) {
      return hash((x & 0xFFFF) << 16) | (y & 0xFFFF);
   }

    static int indexFor(int h, int length) {
        return h & (length-1);
    }

   public void clear() {
      for (int i = 0; i < table.length; i++) {
         table[i] = null;
      }
      size = 0;
   }

   public UserLayer.Tile lookup(int x, int y, boolean createIfNotExist) {
      int hash = getPointHash(x, y);
      Entry e;
      int index = indexFor(hash, table.length);
      for (e = table[index]; e != null; e = e.next) {
         if (e.hash == hash && e.x == x && e.y == y) {
            return e.value;
         }
      }

      if (createIfNotExist) {
         UserLayer.Tile val = new UserLayer.Tile();
         table[index] = new Entry(table[index], x, y, hash, val);

         size++;
         return val;
      }

      return null;

   }

   public int size() {
      return size;
   }

   public boolean isEmpty() {
      return size == 0;
   }

   public Iterator<Entry> entryIterator() {
      return new EntryIterator();
   }

   public Iterator<UserLayer.Tile> valueIterator() {
      return new ValueIterator();
   }

   public Iterator<Void> keyIterator() {
      return new KeyIterator();
   }

    private abstract class HashIterator<E> implements Iterator<E> {
        Entry next;   // next entry to return
       int index;      // current slot
       Entry current;   // current entry

        HashIterator() {
            if (size > 0) { // advance to first entry
               Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry nextEntry() {
            Entry e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
       current = e;
            return e;
        }

        public void remove() {
         throw new UnsupportedOperationException("My Dick");
        }

    }

    private final class ValueIterator extends HashIterator<UserLayer.Tile> {
        public UserLayer.Tile next() {
            return nextEntry().value;
        }
    }

    private final class KeyIterator extends HashIterator<Void> {
        public void next(Point p) {

        }

      public Void next() {
         throw new UnsupportedOperationException("My Dick");
      }
    }

    private final class EntryIterator extends HashIterator<Entry> {
        public Entry next() {
            return nextEntry();
        }
    }


}


replace UserLayer.Tile with whatever obj type you need

HTH

- David
8  Game Development / Game Mechanics / Re: Slight jerkiness on: 2011-07-28 11:17:43
I've had this problem, and apparently it's a bug in Windows ever since 98.

This is how I fixed it:

1  
2  
3  
4  
new Thread() {
{ setDaemon(true); start(); }
public void run() { while(true) {try {Thread.sleep(Integer.MAX_VALUE);}catch(Throwable t){} } }
};


add this in main, before anything loads.
9  Game Development / Newbie & Debugging Questions / Re: how to read keyboard and mouse input when window not in focus( if possible?) on: 2011-07-28 10:49:53
Well, first off I know a lot of you think I am writing  keylogger, and I s'pose I technically am. BUT not for any illegal intentions I assure you.

My plan is to write 2 programs, on the reads input, and then saves everything I did (or atleast the basics of it), and then another that reads the file and does the stuff(this one I know how to do).

But when I thought about itm ore, I realized that I wouldn't be able to listen to the input because my program would not be in focus.

So, if anybody has any suggestions, I would be very grateful Smiley

Thanks in advance,
h3ckboy

here

1  
2  
3  
4  
5  
package yourpckage;

class yourclass {
 public static native int GetAsyncKeyState ( int v );
}


and

1  
2  
JNIEXPORT jint JNICALL Java_yourpackage_yourclass_GetAsyncKeyState
  (JNIEnv *, jclass, jint v) { return GetAsyncKeyState(v); }


remember to #include < windows.h > !!

example of usage:

1  
2  
3  
4  
5  
6  
for (int i = 0; i < 256; i++) {
 final int vk = VK_BASE + i;
 if (yourpackage.yourclass.GetAsyncKeyState(vk) > 0) {
   fireKeyDown(vk);
 }
}


define VK_BASE to be the base of all virtual keys you want to read.

- David
10  Discussions / Business and Project Management Discussions / Re: Advertising/Marketing for Mobile Games on: 2011-07-26 10:20:48
make some viral facebook pages (preferably a lot with 100k+ likes) and then post your links on the facebook pages = profit

(you have to understand current social situations, etc for this to work though.)
11  Game Development / Shared Code / Re: some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-25 12:00:47
Right, license headers changed to All-Permissive in RGBMath and RGBComposite

http://code.google.com/p/praxis/source/browse/ripl/src/net/neilcsmith/ripl/rgbmath/RGBComposite.java
http://code.google.com/p/praxis/source/browse/ripl/src/net/neilcsmith/ripl/rgbmath/RGBMath.java

I haven't look at adding in any of your changes or additional blend modes yet.  Did try various versions of the code you posted with continuously overlaying yellow but can definitely not replicate the drift to red - must be something we're doing differently outside of this code.

Incidentally, as I was posting it in another topic, have you seen the various blend modes from http://filthyrichclients.org/ -> Examples -> Chapter 6.  They're for using with Java2D and aren't as optimal as the code we've got between us, but there might be some good pointers to some missing blend modes in there.

Best wishes,  Neil

thanks. I noticed the drift to red only happened when I used darkish yellow colors, eg 0xffffaa00, it didnt happen when I used brighter yellows.

Took a look at their blendcomposite class and it seems like their blender would be orders of magnitudes slower than the one we have between us, though I agree it would help us write more blend modes. will write more blend modes when I get some time Smiley

- David
12  Game Development / Shared Code / Re: some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-25 03:11:25
I am interested, though, in why we're getting different results.  I wonder what we're doing differently Huh  I'll be doing some work on Praxis in a couple of days, so might try plugging in your altered blend function and see if that causes it, but I can't see at the moment why any of your optimisation changes would alter the behaviour.  That altered mult() method, while more accurate, is also going to slow things down, and negate the optimisations you've made elsewhere - if something else is the root cause, it seems a shame to change it!

yeah, I can only try to optimize further now, but in my application accuracy is more important than speed - in yours probably not so much as you need to render frames at a fast rate.
If I optimize anything further I'll post it here Smiley

- David
13  Game Development / Newbie & Debugging Questions / Re: Character movement with Mouse on: 2011-07-24 13:03:04
and now to move towards the point

1  
2  
3  
4  
5  
x += movex;
y += movey;
if (x == mouseX && y == mouseY) { // you can use epsilon here
stop();
}


hth
That is NOT going to work. In 99.999999999999% of all cases it will just overshoot and continue forever. You would need to change the if-statement to detect overshooting and then set the position to (mouseX, mouseY) to actually land on the mouse position.

thats why I also write use an epsilon here in the comment, its up to OP to implement an epsilon though.

- David
14  Game Development / Shared Code / Re: some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-24 12:08:32
yea I was experimenting and happened to come up with that. I noticed an extremely different result - sometimes I used the color 0xffffaa00 with an opacity of 50% and after stroking a couple times, it became red (0xffff0000) which was obviously a major bug for a drawing application.

After switching to this method for mult, it stayed dark yellow instead of changing to red after a certain number of strokes.

 - David

I just had a quick test in Praxis as this would be a fairly serious bug for me too, but I can't reproduce this effect using my original code.  I assume you're using Normal / SrcOver blend mode for this?  I only see this effect (just red) when the opacity goes below 2%, when rounding errors really start to kick in - no way around that while using an integer pipeline.  Could it be errors in the premultiply() -> unpremultiply() causing it to round down?

yeah I am using SrcOver. it also happens when I use premultiplied colors (eg: not calling the premultiply and unpremultiply functions)

switching to the mult function I posted above fixed it.
15  Java Game APIs & Engines / Java 2D / Re: Loading custom font security issues on: 2011-07-24 07:55:12
Thanks for the reply David. That sounds like a good way to do it.
I found another way too:

1  
2  
3  
4  
5  
6  
7  
8  
URL url = null;
      try
      {
         url = new URL(getCodeBase(), "font.ttf");
         InputStream in=url.openStream();
         m_font = Font.createFont(Font.TRUETYPE_FONT,in).deriveFont(20f);
      }
      catch (Exception e) {}


no worries, glad i could help.
16  Game Development / Newbie & Debugging Questions / Re: Character movement with Mouse on: 2011-07-24 07:40:32
first you need to find the angle

1  
double angle = Math.atan2(mouseY-playerY,mouseX-playerX);


then you need to build a vector to calculate the movement threshold

1  
2  
double movex = Math.cos(angle);
double movey = Math.sin(angle);


and now to move towards the point

1  
2  
3  
4  
5  
x += movex;
y += movey;
if (x == mouseX && y == mouseY) { // you can use epsilon here
stop();
}


hth
17  Game Development / Shared Code / Re: some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-23 17:30:39
this seems to be a more accurate alternative to your mult():

1  
2  
3  
4  
   public static int mult(int a, int b) {
      int t = a * b + 128;
      return (t >> 8) + t >> 8;
   }


Interesting.  Is that yours or from a particular source?

Tried a few values at random and does seem to be slightly more accurate, though only 1 away on all that I tried - have you noticed any greater difference?

Personally, it's unlikely I'll use that fix as it's adding 2 extra operations every time it's called - which is going to add up considering this method may be called 8 or more times per pixel.  I'm not even sure about adding in the +1 fix we had in the previous thread.  But then our use cases are slightly different - I'm working with video so am wanting to process many full frames per second, whereas I can understand accuracy being a greater concern in your application.

yea I was experimenting and happened to come up with that. I noticed an extremely different result - sometimes I used the color 0xffffaa00 with an opacity of 50% and after stroking a couple times, it became red (0xffff0000) which was obviously a major bug for a drawing application.

After switching to this method for mult, it stayed dark yellow instead of changing to red after a certain number of strokes.

 - David
18  Game Development / Shared Code / Re: some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-23 13:43:44
this seems to be a more accurate alternative to your mult():

1  
2  
3  
4  
   public static int mult(int a, int b) {
      int t = a * b + 128;
      return (t >> 8) + t >> 8;
   }
19  Java Game APIs & Engines / Java 2D / Re: Loading custom font security issues on: 2011-07-23 13:27:10
Hi, I have this code here that works fine offline, but fails online because of security IO issues.
1  
font = Font.createFont(Font.TRUETYPE_FONT,new File("font.ttf")).deriveFont(20f);


I think the problem is that it is trying to load the font from the user's file system instead of from the server. How can I fix this?
thanks  Smiley


try putting the font in the jar then using getClass().getClassLoader().getResourceAsStream( ... ) and passing the stream into createFont instead. the accesscontrolcontext created by createFont with an input stream should have temp folder write permission.

HTH

 - David
20  Game Development / Shared Code / Re: some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-23 12:03:35
I pass in source pixels as single values because it seems easier that way, I don't have to write a massive loop around every single function which reads each source pixel, etc.

and if you need to use a source array, it should be easy to add that anyhow. also there are no virtual calls in this class, which removes the overhead of a vtable (hotspot should inline the calls).

OK. Makes sense. I'm just used to pushing the loop into the composite method because I needed RGBComposite to be an abstract class. I'll port some of your optimisations and other blend modes back to mine, so if people want to work with arrays then that's already there - I'm used to passing in scanlines or whole regions at a time.

go ahead. I just wanted it to modify one pixel at a time because that seemed the most flexible to me. For example, in my project I have to construct a source pixel when blending (for example when mixing brush alpha with brush color: int source = alpha<<24|(color&0x00ffffff) ). I don't want to have to make an array each time I just want to modify a single pixel in a specific location.
21  Game Development / Shared Code / Re: some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-23 11:29:24
Hi,

Cool!  For the avoidance of any doubt when I'm next working on Praxis I'll add an all-permissive header rather than GPL to the RGBMath class, and the RGBComposite as well (not sure if you've taken anything from there too?)  Guess by posting here you're happy for your code to be used in any way too.  Be good to get some optimal version of all these blend modes in one place - notice you've got some additional optimisations to me in various places, and also some additional modes.  I think you're missing Sub, Difference and BitXor from my RGBComposite class?  Both Sub and Difference I use a lot - BitXor is a bit of a psychedelic experiment!  Somewhere, I've also got code for an equivalent of Ghost from Director (not sure if that has another name elsewhere).

I think the premultiply() code is going to suffer from the same off by 1 error we discussed in previous thread - I guess that multRGB() should use mult().  Because my pipeline is premultiplied I'm only using that code in one specific place and hadn't noticed the issue.

Is there a reason you're passing in source pixels as single values rather than as an array?  I assume you're not very often working with only a single pixel.

Best wishes, Neil

thanks.

by posting the code here, I'm just saying i'm happy for anyone to do anything they want with the code (as long as your RGBMath class is licensed that way too), just hoping that this might help some people out should they ever need it.

I took some code out of RGBComposite too, but rewrote it to use a single if statement, added a function called blendOneMinus (which doesnt require a sub instruction)

I'll add your Sub, Difference and BitXor to the class if you don't mind.

I pass in source pixels as single values because it seems easier that way, I don't have to write a massive loop around every single function which reads each source pixel, etc.

and if you need to use a source array, it should be easy to add that anyhow. also there are no virtual calls in this class, which removes the overhead of a vtable (hotspot should inline the calls).

 - David
22  Game Development / Shared Code / some new blendmodes (add, multiply, overlay, etc..) on: 2011-07-23 09:32:35
this class allows you to add new blendmodes to java. included are:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
   public static enum Mode {
      Normal,
      Add,
      Multiply,
      Erase,
      Average,
      Overlay,
      Screen,
      Glow,
      Reflect,
      Red,
      Green,
      Blue,
      ColorDodge,
      ColorBurn,a
      HardLight,
   }


supports both premultiplied and unpremultiplied colors.

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  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
331  
332  
333  
334  
335  
336  
337  
338  
339  
340  
341  
342  
343  
344  
345  
346  
347  
348  
349  
350  
351  
352  
353  
354  
355  
356  
357  
358  
359  
360  
361  
362  
363  
364  
365  
366  
367  
368  
369  
370  
371  
372  
373  
374  
375  
376  
377  
378  
379  
380  
381  
382  
383  
384  
385  
386  
387  
388  
389  
390  
391  
392  
393  
394  
395  
396  
397  
398  
399  
400  
401  
402  
403  
404  
405  
406  
407  
408  
409  
410  
411  
412  
413  
414  
415  
416  
417  
418  
419  
420  
421  
422  
423  
424  
425  
426  
427  
428  
429  
430  
431  
432  
433  
434  
435  
436  
437  
438  
439  
440  
441  
442  
443  
444  
445  
446  
447  
448  
449  
450  
451  
452  
453  
454  
455  
456  
457  
458  
459  
460  
461  
462  
463  
464  
465  
466  
467  
468  
469  
470  
471  
472  
473  
474  
475  
476  
477  
478  
479  
480  
481  
482  
483  
484  
485  
486  
487  
488  
489  
490  
491  
492  
493  
494  
495  
496  
497  
498  
499  
500  
501  
502  
503  
504  
505  
506  
507  
508  
509  
510  
511  
512  
513  
514  
515  
516  
517  
518  
519  
520  
521  
522  
523  
524  
525  
526  
527  
528  
529  
530  
531  
532  
533  
534  
535  
536  
537  
538  
539  
540  
541  
542  
543  
544  
545  
546  
547  
548  
549  
550  
551  
552  
553  
554  
555  
556  
557  
558  
559  
560  
561  
562  
563  
564  
565  
566  
567  
568  
569  
570  
571  
572  
573  
574  
575  
576  
577  
578  
579  
580  
581  
582  
583  
584  
585  
586  
587  
588  
589  
590  
591  
592  
593  
594  
595  
596  
597  
598  
599  
600  
601  
602  
603  
604  
605  
606  
607  
608  
609  
610  
611  
612  
613  
614  
615  
616  
617  
618  
619  
620  
621  
622  
623  
624  
625  
626  
627  
628  
629  
630  
631  
632  
633  
634  
635  
636  
637  
638  
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


package as.blend;

/**
 *
 * @author David
 */

public class Compositor {
   public static final int ALPHA_MASK = 0xff000000;
   public static final int RED_MASK = 0x00ff0000;
   public static final int GREEN_MASK = 0x0000ff00;
   public static final int BLUE_MASK = 0x000000ff;

   public static enum Mode {
      Normal,
      Add,
      Multiply,
      Erase,
      Average,
      Overlay,
      Screen,
      Glow,
      Reflect,
      Red,
      Green,
      Blue,
      ColorDodge,
      ColorBurn,
      HardLight,
   }

   public static int premultiply(int argb) {
      int a = argb >>> 24;

      if (a == 0) {
         return 0;
      } else if (a == 255) {
         return argb;
      } else {
         return (a << 24) | multRGB(argb, a);
      }
   }

   public static int multRGB(int src, int multiplier) {
      multiplier++;
      return ((src & RED_MASK) * multiplier) >> 8 & RED_MASK
            | ((src & GREEN_MASK) * multiplier) >> 8 & GREEN_MASK
            | ((src & BLUE_MASK) * multiplier) >> 8;
   }

   public static void blendPixelPremultiplied(int [] pixels, int offset, int srcPx, int alpha, Mode mode) {
      switch (mode) {
         case Normal:
            blendPixel_SrcOver(pixels, offset, srcPx, alpha); return;
         case Add:
            blendPixel_Add(pixels, offset, srcPx, alpha); return;
         case Multiply:
            blendPixel_Multiply(pixels, offset, srcPx, alpha); return;
         case Erase:
            blendPixel_DstOut(pixels, offset, srcPx, alpha); return;
         case Average:
            blendPixel_Average(pixels, offset, srcPx, alpha); return;
         case Overlay:
            blendPixel_Overlay(pixels, offset, srcPx, alpha); return;
         case Screen:
            blendPixel_Screen(pixels, offset, srcPx, alpha); return;
         case Glow:
            blendPixel_Glow(pixels, offset, srcPx, alpha); return;
         case Reflect:
            blendPixel_Reflect(pixels, offset, srcPx, alpha); return;
         case Red:
            blendPixel_Red(pixels, offset, srcPx, alpha); return;
         case Green:
            blendPixel_Green(pixels, offset, srcPx, alpha); return;
         case Blue:
            blendPixel_Blue(pixels, offset, srcPx, alpha); return;
         case ColorBurn:
            blendPixel_ColorBurn(pixels, offset, srcPx, alpha); return;
         case ColorDodge:
            blendPixel_ColorDodge(pixels, offset, srcPx, alpha); return;
         case HardLight:
            blendPixel_HardLight(pixels, offset, srcPx, alpha); return;
      }
      throw new BlendModeNotAvailableException(mode);
   }

   public static class BlendModeNotAvailableException extends RuntimeException {
      public BlendModeNotAvailableException(Mode mode) {
         super(mode + " is not available");
      }
   }

   /**
    * blends two non premultiplied colors together
    * @param pixels
    * @param offset
    * @param srcPx
    * @param alpha
    * @param mode
    */

   public static void blendPixelUnpremultiplied(int[] pixels, int offset, int srcPx, int alpha, Mode mode) {
      pixels[offset] = premultiplyEx(pixels[offset]);
      blendPixelPremultiplied(pixels, offset, premultiplyEx(srcPx), alpha, mode);
      pixels[offset] = unpremultiply(pixels[offset]);
   }

   public static void blendPixel_SrcOver(int pixels[], int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      final int oneMinusSrcA = 0xff - srcA;

      pixels[offset] =
            (blendOneMinus(srcA, destA, oneMinusSrcA) << 24
            | blendOneMinus(srcR, destR, oneMinusSrcA) << 16
            | blendOneMinus(srcG, destG, oneMinusSrcA) << 8
            | blendOneMinus(srcB, destB, oneMinusSrcA));
   }

   /**
    * Blends pixel using DstOut algorithm
    * @param pixels
    * @param offset
    * @param srcPx
    * @param alpha
    */

   public static void blendPixel_DstOut(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      if (alpha != 255) {
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

        final int oneMinusAsAe = 0xff - mult(alpha, srcA);

      pixels[offset] =
            ( mult(destA, oneMinusAsAe) << 24
            | mult(destR, oneMinusAsAe) << 16
            | mult(destG, oneMinusAsAe) << 8
            | mult(destB, oneMinusAsAe));

   }

   public static void blendPixel_Average(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            ( (srcA + destA) << 23
            | (srcR + destR) << 15
            | (srcG + destG) << 7
            | (srcB + destB) >> 1);
   }

   public static void blendPixel_Multiply(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      final int oneMinusSrcA = 0xff - srcA,
              oneMinusDstA = 0xff - destA;
      pixels[offset] =
            blend(srcA, destA, srcA) << 24 |
            (mult(srcR, destR) + mult(destR, oneMinusSrcA) + mult(srcR, oneMinusDstA)) << 16 |
            (mult(srcG, destG) + mult(destG, oneMinusSrcA) + mult(srcG, oneMinusDstA)) << 8 |
            mult(srcB, destB) + mult(destB, oneMinusSrcA) + mult(srcB, oneMinusDstA);
   }

   public static void blendPixel_Add(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(srcA + destA, 0xff) << 24 |
            min(srcR + destR, 0xff) << 16 |
            min(srcG + destG, 0xff) << 8 |
            min(srcB + destB, 0xff);
   }

   public static void blendPixel_Overlay(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      /*
      if a < 128 then
        result := (a*b) SHR 7
      else
        result := 255 - ((255-a) * (255-b) SHR 7);
      */

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            overlay(srcR, destR) << 16 |
            overlay(srcG, destG) << 8 |
            overlay(srcB, destB);
   }

   public static void blendPixel_Screen(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      /*
        result := 255 - ((255-a) * (255-b) SHR 7);
      */

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            screen(srcR, destR) << 16 |
            screen(srcG, destG) << 8 |
            screen(srcB, destB);
   }

   public static void blendPixel_Reflect(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            reflect(srcR, destR) << 16 |
            reflect(srcG, destG) << 8 |
            reflect(srcB, destB);
   }

   public static void blendPixel_Glow(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] = // inverse reflect
           min(255, srcA + destA) << 24 |
            reflect(destR, srcR) << 16 |
            reflect(destG, srcG) << 8 |
            reflect(destB, srcB);
   }

   public static void blendPixel_ColorDodge(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            colordodge(srcR, destR) << 16 |
            colordodge(srcG, destG) << 8 |
            colordodge(srcB, destB);
   }

   public static void blendPixel_ColorBurn(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            colorburn(srcR, destR) << 16 |
            colorburn(srcG, destG) << 8 |
            colorburn(srcB, destB);
   }

   public static void blendPixel_Darken(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            min(srcR, destR) << 16 |
            min(srcG, destG) << 8 |
            min(srcB, destB);
   }

   public static void blendPixel_Lighten(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            max(srcR, destR) << 16 |
            max(srcG, destG) << 8 |
            max(srcB, destB);
   }

   public static void blendPixel_Red(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            srcR << 16 |
            destG << 8 |
            destB;
   }

   public static void blendPixel_Green(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      if (alpha != 255) {
         srcG = mult(srcG, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            destR << 16 |
            srcG << 8 |
            destB;
   }

   public static void blendPixel_Blue(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;

      pixels[offset] =
            min(255, srcA + destA) << 24 |
            destR << 16 |
            destG << 8 |
            srcB;
   }

   public static void blendPixel_HardLight(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            min(0xff, srcA + destA) << 24 |
            hardlight(srcR, destR) << 16 |
            hardlight(srcG, destG) << 8 |
            hardlight(srcB, destB);
   }

   public static void blendPixel_Difference(int [] pixels, int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] =
            blend(srcA, destA, srcA) << 24 |
               (srcR + destR - (2 * min(mult(srcR, destA), mult(destR, srcA)))) << 16 |
               (srcG + destG - (2 * min(mult(srcG, destA), mult(destG, srcA)))) << 8 |
               (srcB + destB - (2 * min(mult(srcB, destA), mult(destB, srcA))));
   }

   public static int hardlight(int a, int b) {
      return a < 128 ? (a * b) >> 7 : 0xff - ((0xff-a) * (0xff-b) >> 7);
   }

   public static int reflect(int a, int b) {
      return b == 255 ? 255 : min(255, a * a / (255 - b));
   }
   
   public static int colorburn(int a, int b) {
      return b == 0 ? 0 : max(0, (0xff - ((0xff-a) << 8)/ b));
   }

   public static int colordodge(int a, int b) {
      return b == 0xff ? 0xff : min(0xff, ((a<<8) / (0xff-b)));
   }

   public static int overlay(int a, int b) {
      if (a < 128) {
         return (a * b) >> 7;
      } else {
         return 0xff - (((0xff-a) * (0xff-b)) >> 7);
      }
   }

   public static int screen(int a, int b) {
      return 0xff - mult(a, b);
   }

   public static int min(int a, int b) {
      return a < b ? a:b;
   }

   public static int max(int a, int b) {
      return a > b ? a:b;
   }

   public static int blendOneMinus(int src, int dest, int oneMinus) {
      return src + mult(dest, oneMinus);
   }

   public static int blend(int src, int dest, int alpha) {
      return src + mult(dest, 0xFF - alpha);
   }

   public static int mult2(int val, int multiplier) {
      return (val * (multiplier + 1)) >> 8;
   }

   public static int mult(int a, int b) {
      final int t = a * b + 128;
      return (t >> 8) + t >> 8;
   }

   public static int premultiplyEx(int rgb) {
      return premultiply(rgb, rgb>>>24);
   }

   public static int premultiply(int rgbColor, int alpha) {

      if (alpha <= 0) {
         return 0;
      } else if (alpha >= 255) {
         return 0xff000000 | rgbColor;
      } else {
         int r = (rgbColor >> 16) & 0xff;
         int g = (rgbColor >> 8) & 0xff;
         int b = rgbColor & 0xff;

         r = (alpha * r + 127) / 255;
         g = (alpha * g + 127) / 255;
         b = (alpha * b + 127) / 255;
         return (alpha << 24) | (r << 16) | (g << 8) | b;
      }
   }

   public static int unpremultiply(int preARGBColor) {
      int a = preARGBColor >>> 24;

      if (a == 0) {
         return 0;
      } else if (a == 255) {
         return preARGBColor;
      } else {
         int r = (preARGBColor >> 16) & 0xff;
         int g = (preARGBColor >> 8) & 0xff;
         int b = preARGBColor & 0xff;

         r = 255 * r / a;
         g = 255 * g / a;
         b = 255 * b / a;
         return (a << 24) | (r << 16) | (g << 8) | b;
      }
   }
}


mult and blend functions taken from praxis (http://code.google.com/p/praxis/source/browse/ripl/src/net/neilcsmith/ripl/rgbmath/RGBMath.java)

reference: http://www.pegtop.net/delphi/articles/blendmodes/intro.htm

example:

1  
2  
3  
4  
5  
int [] destination = .. // your destination array
int source = 0x80ff0000; // red with 50% opacity, can be any color
int offset = 0x20; // offset in destination array to blend
int extraAlpha = 100; // extra alpha to blend with
blendPixelPremultiplied(destination, offset, source, extraAlpha, Mode.Multiply);


the above code blends the pixel in offset 0x20 with the color red, with 50% opacity, adding 100 extra alpha while blending, using the multiply blendmode.
23  Game Development / Newbie & Debugging Questions / Re: Storing player data on: 2011-07-21 12:52:40
Nice post Dx4 but it'll still be possible to backwards engineer and change the save file.


obviously, people who want to hack your game and are dedicated enough WILL be able to, it's impossible to protect it from everyone, but with what I wrote above when mixed with some fancy obfuscation will prove to be a very burdensome task to reverse engineer and change.

- David
24  Game Development / Newbie & Debugging Questions / Re: Storing player data on: 2011-07-21 09:55:54
Im working on a rpg game and i have a problem, storing player data.
I was thinking about storing save games in plain text files within the jar or in directories placed near the jar file, but that would be really easy for the player to modify, which will make the game less challenging and less fun. I have been thinking about serelization as well, but i don't know anything about serelization and it seems awfully complicated. Is there any other alternatives?

Sign the jar, and save the game state as a class using ObjectWeb ASM (or some other class modifying library). Replace the game state class file within the JAR, and generate a new checksum for the file. Save the checksum into MANIFEST.MF. When they try to modify the saved game state (which I doubt many could), save it and then try to run it again, the JVM will crash as the checksum for the class doesn't match. For extra security, check manifest.mf when the game starts and do a file integrity check on each file in the JAR file against the entries in the manifest. This will also ensure that people can't just remove the signing on the jar.

Example class:

1  
2  
3  
4  
public class State {
 private static int numLives = 100;
 private static int health = 100; .. etc
}


then use a class modifier to rewrite the values in the state class.

Alternatively, just use XML or OOS to save the state, and use JCE (DES, AES256, etc) to encrypt the data using a key generated with some special data, eg last modified time of the executing jar, OS type, etc

for example:

1  
byte[] key = md5(System.getProperty("user.name") + System.getProperty("os.arch"));
25  Game Development / Newbie & Debugging Questions / Re: Alpha blending on: 2011-07-20 19:11:49
That project looks pretty sweet!  Though MySQL seems to be down on your server at the moment.

Your experience on switching from Java2D is similar to mine - huge speed up - lots of things become faster (or even possible!)

it is down. subscription on my dedicated server expired Tongue i have yet to renew it

but you can still view the gallery - my artist drew those images in UxPaint: http://uxpaint.com/gallery

This is the most i've optimized the algorithm so far:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
   private void blendPixelEXT(int pixels[], int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      int srcA = srcPx >>> 24;
      int srcR = (srcPx & RED_MASK) >>> 16;
      int srcG = (srcPx & GREEN_MASK) >>> 8;
      int srcB = (srcPx & BLUE_MASK);
      if (alpha != 255) {
         srcR = mult(srcR, alpha);
         srcG = mult(srcG, alpha);
         srcB = mult(srcB, alpha);
         srcA = mult(srcA, alpha);
      }
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] = (blend(srcA, destA, srcA) << 24
            | blend(srcR, destR, srcA) << 16
            | blend(srcG, destG, srcA) << 8
            | blend(srcB, destB, srcA));
   }
26  Discussions / General Discussions / Re: UxPaint - new collaborative paint program in development on: 2011-07-20 19:04:26
Update:

Added square brush, and switched the entire rendering system to software instead of Java2D.






 - David
27  Game Development / Newbie & Debugging Questions / Re: Alpha blending on: 2011-07-20 18:55:23

Incidentally, what are you writing a software renderer for?  A project of its own or something bigger?

And I know I mentioned it before, but I'd really recommend moving to premultiplied data throughout - it's easier and better performing - trust me, I found out the hard way!  Grin


I'm writing a software renderer to handle the brushes for my project:

http://www.java-gaming.org/topics/uxpaint-new-collaborative-paint-program-in-development/24478/view.html

I wasn't happy with the performance of Java2D, especially in regards to colorizing images on the fly; therefore I had to devise something much faster.

Now that I have switched to a software renderer, I get the following benefits:

  • Able to use any blendmode I want for brushes (Add, Multiply, Over, Overlay, Screen, Darken, etc)
  • Able to save the state of any pixels I modify without doing a scan beforehand (VERY useful for undo states)
  • Able to colorize brush pixels on the fly using a simple OR operation: (source << 24) | color, previously in Java2D I had to create a new image, get a graphics context, set alphacomposite, set color and call drawLine(x,y,x,y) for each pixel I wanted to recolor. INSANE speed increase in brush rendering once I made the switch.
  • Uses much less memory, each brush image (with colors, etc) took about 4kb memory before, and about 1000 would be created for a single stroke, equal to 4MB. With my new software renderer, it is able to use a constant 400kb per brush (for 100 sizes)

overall, the software renderer is about 15x faster than Java2D and also supports blendmodes, state saving, etc, its a win-win situation.

I might switch to TYPE_ARGB_PRE later, if required, but I've actually tried it before and it results in weird artifacts when I zoom in, i'll save it for investigation on another day Smiley

BTW: Brush class is now:

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  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
package as.internal.unnatural;

import as.internal.UndoManager.UndoState;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.util.Arrays;

/**
 *
 * @author David
 */

public class Brush {

   private int[][] brushData;
   private int maxPixelValue;
   public static int TypeRound = 1,
         TypeSquare = 2;

   public static Brush getSquareBrush(int count) {
      return new Brush(count, TypeSquare, false);
   }

   public static Brush getRoundBrush(int count) {
      return new Brush(count, TypeRound, true);
   }

   private Brush(int numSizes, int type, boolean antialias) {
      brushData = new int[numSizes][];
      for (int i = 1; i <= numSizes; i++) {
         BufferedImage brush = new BufferedImage(i, i, BufferedImage.TYPE_INT_ARGB);
         Graphics2D g = brush.createGraphics();
         if (antialias) {
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
         }
         g.setColor(Color.BLACK);
         g.setComposite(AlphaComposite.Src);
         if (type == TypeRound) {
            g.fillOval(0, 0, i, i);
         } else if (type == TypeSquare) {
            g.fillRect(0, 0, i, i);
         }
         g.dispose();
         int array[] = ((DataBufferInt) brush.getRaster().getDataBuffer()).getData();
         brushData[i - 1] = Arrays.copyOf(array, array.length);
         int[] data = brushData[i - 1];
         for (int j = 0; j < data.length; j++) {
            data[j] >>>= 24;
            if (data[j] > maxPixelValue) {
               maxPixelValue = data[j];
            }
         }
         brush.flush();
      }
   }

   public Brush(BufferedImage image, int numSizes) {
      brushData = new int[numSizes][];
      for (int i = 1; i <= numSizes; i++) {
         BufferedImage brush = new BufferedImage(i, i, BufferedImage.TYPE_INT_ARGB);
         Graphics2D g = brush.createGraphics();
         g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
         g.drawImage(image, 0, 0, i, i, null);
         g.dispose();
         int array[] = ((DataBufferInt) brush.getRaster().getDataBuffer()).getData();
         brushData[i - 1] = Arrays.copyOf(array, array.length);
         int[] data = brushData[i - 1];
         for (int j = 0; j < data.length; j++) {
            data[j] >>>= 24;
            if (data[j] > maxPixelValue) {
               maxPixelValue = data[j];
            }
         }
         brush.flush();
      }
   }

   public int getPixelMaxAlpha() {
      return maxPixelValue;
   }

   public int getMaxBrushSize() {
      return brushData.length + 1;
   }

   int clamp(int value) {
      return value > 255 ? 255 : value;
   }

   public static int premultiply(int rgbColor, int alpha) {

      if (alpha <= 0) {
         return 0;
      } else if (alpha >= 255) {
         return 0xff000000 | rgbColor;
      } else {
         int r = (rgbColor >> 16) & 0xff;
         int g = (rgbColor >> 8) & 0xff;
         int b = rgbColor & 0xff;

         r = (alpha * r + 127) / 255;
         g = (alpha * g + 127) / 255;
         b = (alpha * b + 127) / 255;
         return (alpha << 24) | (r << 16) | (g << 8) | b;
      }
   }

   public static int unpremultiply(int preARGBColor) {
      int a = preARGBColor >>> 24;

      if (a == 0) {
         return 0;
      } else if (a == 255) {
         return preARGBColor;
      } else {
         int r = (preARGBColor >> 16) & 0xff;
         int g = (preARGBColor >> 8) & 0xff;
         int b = preARGBColor & 0xff;

         r = 255 * r / a;
         g = 255 * g / a;
         b = 255 * b / a;
         return (a << 24) | (r << 16) | (g << 8) | b;
      }
   }

   void alphaBlend(int[] pixels, int offset, int source, int alpha) {
      int destRGB = pixels[offset];
      int destA = destRGB >>> 24;
      //destRGB = premultiply(destRGB, destA);
     int destR = (destRGB >> 16) & 0xff;
      int destG = (destRGB >> 8) & 0xff;
      int destB = destRGB & 0xff;
      int srcA = source >>> 24;
      //source = premultiply(source, srcA);
     int srcR = (source >> 16) & 0xff;
      int srcG = (source >> 8) & 0xff;
      int srcB = source & 0xff;

      srcA *= alpha;
      srcR *= alpha;
      srcG *= alpha;
      srcB *= alpha;

      int oneMinusSrcA = 0xff - (srcA >> 8);

      destR = (srcR + destR * oneMinusSrcA) >> 8;
      destG = (srcG + destG * oneMinusSrcA) >> 8;
      destB = (srcB + destB * oneMinusSrcA) >> 8;
      destA = (srcA + destA * oneMinusSrcA) >> 8;
      //pixels[offset] = (destA << 24) | (destR << 16) | (destG << 8) | destB;
     pixels[offset] = //unpremultiply
           ((destA << 24) | (destR << 16) | (destG << 8) | destB);
   }
   
        /*thanks nsigma*/
   public static final int ALPHA_MASK = 0xff000000;
   public static final int RED_MASK = 0x00ff0000;
   public static final int GREEN_MASK = 0x0000ff00;
   public static final int BLUE_MASK = 0x000000ff;

   public static int premultiply(int argb) {
      int a = argb >>> 24;

      if (a == 0) {
         return 0;
      } else if (a == 255) {
         return argb;
      } else {
         return (a << 24) | multRGB(argb, a);
      }
   }

   public static int premultiplyEXT(int argb, int a) {
      if (a == 0) {
         return 0;
      } else if (a == 255) {
         return argb;
      } else {
         return (a << 24) | multRGB(argb, a);
      }
   }

   public static int multRGB(int src, int multiplier) {
      multiplier++;
      return ((src & RED_MASK) * multiplier) >> 8 & RED_MASK
            | ((src & GREEN_MASK) * multiplier) >> 8 & GREEN_MASK
            | ((src & BLUE_MASK) * multiplier) >> 8;
   }

   private void blendPixelEXT(int pixels[], int offset, int srcPx, int alpha) {
      boolean alpha255 = alpha == 255;
      int destPx = pixels[offset];
      destPx = premultiplyEXT(destPx, (destPx) >>> 24);
      int srcA = srcPx >>> 24;
      srcPx = premultiplyEXT(srcPx, srcA);
      if (alpha255 == false) {
         srcA = mult(srcA, alpha);
      }
      int srcR = (alpha255) ? (srcPx & RED_MASK) >>> 16
            : mult((srcPx & RED_MASK) >>> 16, alpha);
      int srcG = (alpha255) ? (srcPx & GREEN_MASK) >>> 8
            : mult((srcPx & GREEN_MASK) >>> 8, alpha);
      int srcB = (alpha255) ? (srcPx & BLUE_MASK)
            : mult(srcPx & BLUE_MASK, alpha);
      int destA = (destPx) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] = unpremultiply(blend(srcA, destA, srcA) << 24
            | blend(srcR, destR, srcA) << 16
            | blend(srcG, destG, srcA) << 8
            | blend(srcB, destB, srcA));
   }

   public static int blend(int src, int dest, int alpha) {
      return src + mult(dest, 0xFF - alpha);
   }

   public static int mult(int val, int multiplier) {
      return (val * (multiplier + 1)) >> 8;
   }

   public void drawBrush(int x, int y, int size, int alpha, int color, int[] pixels, int width, int height, UndoState state) {
      if (alpha == 0) {
         return;
      }
      int brushIndex = 0;
      int[] brushPixels = brushData[size - 1];
      for (int i = 0; i < size; i++) {
         final int ycoord = y + i;
         if (ycoord < 0 || ycoord >= height) {
            continue;
         }
         for (int j = 0; j < size; j++) {
            int source = (brushPixels[brushIndex++]);
            if (source > 0) {
               final int xcoord = x + j;
               if (xcoord < 0 || xcoord >= width) {
                  continue;
               }
               final int pos = ycoord * width + xcoord;
               state.putPixel(pixels[pos], xcoord, ycoord);
               blendPixelEXT(pixels, pos, (source << 24) | color, alpha);
            }
         }
      }
   }

   public void drawBrush(int x, int y, int size, int alpha, int color, UserLayer layer) {
      if (size <= 0) {
         return;
      }
      int brushIndex = 0;
      int[] brushPixels = brushData[size - 1];
      int limit = (alpha * maxPixelValue) / 255;
      for (int i = 0; i < size; i++) {
         for (int j = 0; j < size; j++) {
            int source = (brushPixels[brushIndex++]);
            if (source > 0) {
               final int xcoord = x + j, ycoord = y + i;
               if (xcoord < 0 || ycoord < 0 || xcoord >= layer.width || ycoord >= layer.height) {
                  continue;
               }
               final int xcoordScaled = xcoord >> 5, ycoordScaled = ycoord >> 5;
               UserLayer.Tile tile = layer.getTileForNoScaling(xcoordScaled, ycoordScaled);
               int offset = ((ycoord - (ycoordScaled << 5)) << 5) + xcoord - (xcoordScaled << 5);
               int destA = tile.pixels[offset] >>> 24;
               destA = source + ((destA * (0xff - source)) >> 8);
               destA = Math.min(limit, destA);
               tile.pixels[offset] = color | (destA << 24);
            }
         }
      }
   }
}


just in case anyone else finds it useful..

David
28  Game Development / Newbie & Debugging Questions / Re: Alpha blending on: 2011-07-20 14:53:24
1  
2  
3  
4  
5  
6  
7  
    public static int blend(int src, int dest, int alpha) {
        return src + (((0xFF - alpha) * dest) >> 8);
    }

    public static int mult(int val, int multiplier) {
        return (val * (multiplier + 1)) >> 8;
    }


I'm thinking of just capping the alpha so the resultant alpha can NEVER be less than the destination alpha.. seems like the easiest way out.

This is probably still rounding errors caused by bitshifting.  Could try -

1  
2  
3  
4  
5  
6  
7  
    public static int blend(int src, int dest, int alpha) {
        return src + mult(dest, 0xFF - alpha);
    }

    public static int mult(int val, int multiplier) {
        return (val * (multiplier + 1)) >> 8;
    }


ie. force it to add 1 to the multiplier.

Haven't been able to test it, but I think it might work.  Should probably evaluate that fix for my code too.

Best wishes, Neil


Thanks so much Neil! That did the trick Smiley

BTW: Slight optimization:

instead of

1  
int destA = (destPx & ALPHA_MASK) >>> 24;


use

1  
int destA = (destPx) >>> 24;


no need to mask it when you know that the left 24 bits will always be zero, same thing applies to srcA.
29  Game Development / Newbie & Debugging Questions / Re: Alpha blending on: 2011-07-20 09:03:58
thanks for the reply.


I've also written my own software renderer.  Just had my first morning coffee so it's a bit early for bitshifting - let's hope this is right ...  Grin

1  
2  
3  
4  
        srcA *= alpha;
        srcR *= alpha;
        srcG *= alpha;
        srcB *= alpha;


This bit looks wrong.  Assuming your alpha value is in the range 0..255, then that needs to be shifted down.

This should be right, as I'm doing a >> 8 shift after, to move it back into the range of a byte.

eg.
1  
  srcA = (srcA * alpha) >> 8;


In my code I'm also doing the equivalent of
1  
  srcA = (srcA * (alpha + 1)) >> 8;

which seems to be more accurate.

I will try this, thanks for spotting that.

The second issue may be that Porter-Duff algorithms expect pre-multiplied colour data.  You haven't mentioned whether the data is pre-multiplied or not (I'd recommend doing so, as it makes a lot of things easier for both you and the CPU).

If your data isn't pre-multiplied then I'd also change the code above to be

1  
2  
3  
4  
        srcA = alpha == 255 ? srcA : (srcA * (alpha + 1)) >> 8;
        srcR = (srcR * (srcA + 1)) >> 8;
        srcG = (srcG * (srcA + 1)) >> 8;
        srcB = (srcB * (srcA + 1)) >> 8;

ie. make sure to multiply colour values by srcA not just alpha.

Hopefully that's all correct - I haven't actually tried it!

This looks interesting. I will take a look into it.

If you're interested in looking at my blending mode code in Praxis, have a look here http://code.google.com/p/praxis/source/browse/ripl/src/net/neilcsmith/ripl/rgbmath/RGBComposite.java.  SrcOver is actually called Normal.  Praxis as a whole is GPL3, but feel free to use anything in this file, or the RGBMath file (which it also needs).

I will definitely take a look at your Praxis project. It looks quite interesting.

Hope that helps.

Best wishes,  Neil

Thanks for your time, Neil



EDIT:

it still results in pixels with less alpha than expected for some reason, when low alpha values are used, try 1

this is the code I used:

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 final int ALPHA_MASK = 0xff000000;
    public static final int RED_MASK = 0x00ff0000;
    public static final int GREEN_MASK = 0x0000ff00;
    public static final int BLUE_MASK = 0x000000ff;

     public static int premultiply(int argb) {
        int a = argb >>> 24;

        if (a == 0) {
            return 0;
        }
        else if (a == 255) {
            return argb;
        }
        else {
            return (a << 24) | multRGB(argb, a);
        }
    }

   public static int multRGB(int src, int multiplier) {
        multiplier++;
        return ((src & RED_MASK) * multiplier) >> 8 & RED_MASK |
                ((src & GREEN_MASK) * multiplier) >> 8 & GREEN_MASK |
                ((src & BLUE_MASK) * multiplier) >> 8;
    }


   private void blendPixelEXT(int pixels[], int offset, int srcPx, int alpha) {
      int destPx = pixels[offset];
      destPx = premultiply(destPx);
      srcPx = premultiply(srcPx);
      int srcA = (alpha == 255) ? (srcPx & ALPHA_MASK) >>> 24
            : mult((srcPx & ALPHA_MASK) >>> 24, alpha);
      int srcR = (alpha == 255) ? (srcPx & RED_MASK) >>> 16
            : mult((srcPx & RED_MASK) >>> 16, alpha);
      int srcG = (alpha == 255) ? (srcPx & GREEN_MASK) >>> 8
            : mult((srcPx & GREEN_MASK) >>> 8, alpha);
      int srcB = (alpha == 255) ? (srcPx & BLUE_MASK)
            : mult(srcPx & BLUE_MASK, alpha);
      int destA = (destPx & ALPHA_MASK) >>> 24;
      int destR = (destPx & RED_MASK) >>> 16;
      int destG = (destPx & GREEN_MASK) >>> 8;
      int destB = (destPx & BLUE_MASK);

      pixels[offset] = unpremultiply(blend(srcA, destA, srcA) << 24 |
            blend(srcR, destR, srcA) << 16 |
            blend(srcG, destG, srcA) << 8 |
            blend(srcB, destB, srcA));
   }

    public static int blend(int src, int dest, int alpha) {
        return src + (((0xFF - alpha) * dest) >> 8);
    }

    public static int mult(int val, int multiplier) {
        return (val * (multiplier + 1)) >> 8;
    }


I'm thinking of just capping the alpha so the resultant alpha can NEVER be less than the destination alpha.. seems like the easiest way out.
30  Game Development / Newbie & Debugging Questions / Alpha blending on: 2011-07-20 05:39:31
ive been writing a software renderer, but it seems like alpha blending isnt working so well..

algorithm for porter-duff SrcOver:

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  
   void alphaBlend(int [] pixels, int offset, int source, int alpha) {
        int destRGB = pixels[offset];
      int destA = destRGB >>> 24;
        int destR = (destRGB >> 16) & 0xff;
        int destG = (destRGB >> 8) & 0xff;
        int destB = destRGB & 0xff;
        int srcA = source >>> 24;
        int srcR = (source >> 16) & 0xff;
        int srcG = (source >> 8) & 0xff;
        int srcB = source & 0xff;

        srcA *= alpha;
        srcR *= alpha;
        srcG *= alpha;
        srcB *= alpha;

        int oneMinusSrcA = 0xff - (srcA >> 8);

        destR = (srcR + destR * oneMinusSrcA) >> 8;
        destG = (srcG + destG * oneMinusSrcA) >> 8;
        destB = (srcB + destB * oneMinusSrcA) >> 8;
      destA = (srcA + destA * oneMinusSrcA) >> 8;
        //pixels[offset] = (destA << 24) | (destR << 16) | (destG << 8) | destB;
     pixels[offset] =
            ((destA << 24) | (destR << 16) | (destG << 8) | destB);
   }


pixel = array of ARGB pixels
offset = position of pixel in array to blend
source = color in ARGB format to blend with destination (pixel[offset])
alpha = alpha to take into account while blending (between 0-255)

the problem is that sometimes it doesn't blend the alpha properly and instead just replaces the destination alpha with source alpha, can anyone see why this happens?

it happens when the source color has a very small alpha value eg: 1

thanks
Pages: [1] 2 3
 

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

The first screenshot will be displayed as a thumbnail.

Dwinin (20 views)
2014-09-12 09:08:26

Norakomi (55 views)
2014-09-10 13:57:51

TehJavaDev (64 views)
2014-09-10 06:39:09

Tekkerue (32 views)
2014-09-09 02:24:56

mitcheeb (54 views)
2014-09-08 06:06:29

BurntPizza (38 views)
2014-09-07 01:13:42

Longarmx (24 views)
2014-09-07 01:12:14

Longarmx (29 views)
2014-09-07 01:11:22

Longarmx (28 views)
2014-09-07 01:10:19

mitcheeb (36 views)
2014-09-04 23:08:59
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!