How should I program a simulation of physics? - java

I am trying to create a Java package that can be used to write simulation programs.
My goal is to create 'objects' like springs or solid objects like cubes and spheres. They will have mass, velocity, gravity etc. and they can interact with each other.
I have seen some simulation programs on www.myphysicslab.com but my problem is that I don't want to write different equations for different senarios. Is there any way to do this? I am new to programming.

Creating a physics engine is hard. (Very hard). But it can also be a lot of fun. Well, fun in a "why am I doing this to myself?" kind of way.
Assuming your have a fair grasp of the maths involved*, and assuming you're interested in Rigid Body Dynamics there are a couple of classic references to start with:
First of all Chris Hecker's Rigid Body Dynamics tutorials
And of course Witkin and Baraff's SIGGRAPH course
Those are good places to start and will provide more than enough of a challenge for you.
You could also look at Box2D by Erin Catto and his associated GDC tutorials which you can download.
For more specific help, the forums for Bullet also contain a sub-section where you can discuss and ask questions once you have understood some of the basics.
*If you don't have this fair grasp, learn. If you're not willing to, don't try and just use an existing engine. If this is your very first programming experience, just focus on the programming first. Don't get yourself overwhelmed.
Good luck.

To understand physics, you must first understand maths. Attempting to write a physics engine without using mathematical equations is like making a cake without ingredients.
Entire careers are built on creating physics engines, so my advice is to either use an existing engine, or get your books out.

Building a physics simulator can be a lot of work. Two dimensions is considerably simpler than three, so maybe you want to start with 2D. You might want to begin with an existing package like JBox2D. It has a constraint solver, friction, etc. You can build on top of JBox2D or study how it works.
An HTML5 version is available with online demos: GWTBox2D

There is a program called Easy Java Simulations
that does exactly what you want!
You can create java applets and has many of the visual objects ready.
You can also write java code and subprograms.
visit http://fem.um.es/Ejs/ to download.

Related

Java MiniGame Hiding Letters

Hey guys im new to Java and atm im creating a Text Adventure game =)
so, to unlock systems i want a feature called minigame.
a black frame should hide letters inside of it and if you mark them with
your mouse you should be able to see them..at the end you have to put
the correct word into a textField.
Can some1 give me some cheats for that? :D
Firstly, I would consider changing the wording of your question because people on here are very sensitive about wording and specificity, which helps us to better answer your question.
I assume that by "cheats" you mean shortcuts to acomplishing this. There is not a very straightforward way to do this in Java, but I would certainly reccommend writing this game using javaScript with the jQuery library. JQuery has a method .hover() that would be very useful here, and you could code the interactive rectangle in html and CSS.
Also, javaScript is similar to Java in case learning Java is your overall goal. That is my "cheat," using these two tools instead of Java for this purpose. Otherwise you would have to use a java graphics library which might be a little complicated for a beginner.
I would reccommend using Code Academy since it was how I originally learned how to develop webpages and was incredibly helpful to me as a beginner: https://www.codecademy.com

How to approach writing algorithm from a complex research paper

I thought of writing a piece of software which does Alpha Compositing. I didn't wanted ready made code off from internet so I tried to find research papers and other sources to understand the mathematical algorithms, and initiated to implement.
But, I got lost very quickly. So my question is,
How should I approach these papers to extract the necessary details from it in order to write algorithm based on it. Any specific set of steps which works well?
Desired answer :
Read ...
Extract ...
Understand ...
Implement ...
Note: This question is not limited to only Alpha Compositing, so more generalised approach will be helpful. I have tagged Java and C++, because thats my desired language to implement the image processing.
What I have done so far?
This is not a homework question but it is of course better to say what I know. I have read wiki of Alpha compositing, and few closely related Image compositing research papers. But, I stuck at the next step to take in order to go from understanding to implementation.
Wikipedia
Technical Memo, Image compositing
I'd recommend reading articles with complex formulas with a pencil and paper. Work through the math involved until you have a good grasp on it. Then, you'll be ready to code.
Start with identifying the steps needed to perform your algorithm on some image data. Include all of the steps from loading the image itself into memory all the way through the complex calculations that you may need to perform. Then structure that list into pseudocode. Once you have that, it should be rather easy to code up.
Write pseudocode. Ideally, the authors of the research papers would have done this, but often they don't. Write pseudocode for some simple language like Matlab or possibly Python, and hack away at writing a working implementation based on the psuedocode.
If you understand some parts of the algorithm but not others, then implement your pseudocode into real code for the parts you understand, and leaving comments for the places you don't.
The section from The Pragmatic Programmer on "Tracer Bullets" basically describes this idea. You want to quickly hack together something that takes your data into some form of an output, and then iterate on the body of the code to get it to slowly resemble the algorithm you're trying to produce.
My answer is necessarily somewhat vague. There's no magic bullet for something like this.
Have you implemented any image processing algorithms? Maybe start with something a little simpler, like desaturation/color intensification, reversal (side to side and upside down), rotating, scaling, and compositing images through a mask.
Once you have those figured out, you will be in a very good position to do an alpha composite.
I agree that academic papers seem to go out of their way to make implementation details muddy and uncertain. I find that large amounts of simplification to what is written is needed to begin to perform a practical implementation. In their haste to be general, writers excessively parameterize every aspect. To build useful, reliable software, it is necessary to start with something simple which actually works so that it can be a framework to add features. To do that, it is necessary to throw away 80–90 percent of the academic generality. Often much can be done with a raft of symbolic constants, but abandoning generality (say for four and five dimensional images) doesn't really lose anything in practice.
My suggestion is to first write the algorithm using Matlab to make sure that you understood all the steps and then try to implement using C++ or java.
To add to the good suggestions above, try to write your pseudocode in simple module (Object oriented style ) so has to have a deep understanding of each part of your code while not loosing the big picture. Writing everything in a procedural way is good a the beginning but as the code grow, it might get become hard to keep up will all you are trying to do.
This example cites one of the seminal works on the topic: Compositing Digital Images by Porter & Duff. The class java.awt.AlphaComposite implements the same rules.

Java: How exactly are character models and the like created in LWJGL?

Think about the games like Spiral Knights and Minecraft(Which I believe both use LWJGL) - How are the characters created? Does, at least Spiral Knights, use some other outside program to make them, then import them somehow? Does Minecraft handle their mob / character creation all in Java or LWJGL(That would make sense to me, since the models are more simple)? I'm confused as to how and where they're made, and the different ways you go about making them. I'm not talking about textures, but the things that the textures are applied to.
Does making the models even use LWJGL?
Please tell me if I misunderstood something, or said something incorrectly that didn't make sense.
It's pretty hard to say without knowing what each individual team's art pipeline looks like. As such I won't try to speculate except to say that as long as you can render 3d geometry, you can surely find or build a routine to import just about any 3d file format: collada, max, maya (mb, ma), .x, ms3d, blend, etc.
The need to consider just 3 things:
Does the 3d tool you're considering support the kind of art you want to create?
Do you or your artist have experience in that tool?
Can you write or find the code to load the 3d file format?
If you can answer those 3 questions positively, then you have a good candidate for the tool to use for this project :-)

Java real time strategy game development

I'm coming to the end of my first year of CS and I thought a great way to consolidate all the things I've learnt this year would be a personal game project.
I would like to implement a 2D based rts, I'm thinking along the lines of starcraft I, warcraft II or even command and conquer. I will have about 3 months without interruptions to implement the game.
So to anyone experienced with java game programming, I have a few questions:
Is it realistic to design a 2D rts engine from scratch in 3 months?
If so what are some good books/resources to get started?
Would it be better to modify some existing project? I would think the experience of having to work with a lot of someone else's code would be good since our exposure to such topics in an undergrad cs degree seems very rare, if non-existent.
Are there any decent open source 2d rts projects that anyone could recommend? I've looked through a few but most seem to be written in c/c++
My humble thanks
Edit: Thanks for the quick responses, I think that perhaps it was a bad idea to post this in a rush since I think I misrepresented what I want to do.
When I say "along the lines of warcraft II etc" I mean more like that style of rts using sprites. I don't intend to implement a game nearly that complex, more like just a basic prototype.
My goal would be some thing more like a flat textured map with some basic obstacles like trees, a single unit producing structure like a barracks. I'd like to have the units to have health bars, be able to move and attack and die (and possible morph into another unit).
Far off goals would be to implement some basic pathing using a modified version of the dijkstra shortest path algorithm, ranged units with missle attack, etc.
I don't plan to implement any opponents or ai or networking or anything like that.
I'm thinking along the lines of starcraft I, warcraft II or even command and conquer
Make sure you purge your mind of matching the full scope of any of those. They took large teams of developers multiple years to make, with multi-million dollar budgets, so you can't even hope to approach those. They're called AAA for a reason. That being said, there's no reason you can't very minimally ape their design, or make a tiny game in their genre, assuming you have previous experience making small games.
A sub-genre of RTS that might be doable in that amount of time is a Tower Defense game. Plants vs Zombies is a good example. The reason I suggest this sub-genre is that you can avoid implementing any sort of AI or path-finding, which are notoriously difficult to get working, and I think technically impossible to implement "perfectly", especially with a limited CPU budget.
Make sure to reign in your scope. Favor a "complete" game over new features, because you can then call it "done" at any time. Get your game playable ASAP, and don't sweat the polish or details until you have to. Add one enemy type and one type of player unit (with only one ability, if you were thinking of implementing multiple abilities per unit). Make a title screen, menus (even if the menu is just "click screen to play"), game over screen, level complete or stat screens, cross-level player statistics, etc. Once you have all that ironed out, spend equal time adding new features and polishing the gameplay/graphics/bugs.
Once you have a playable, "complete" game ready (no matter how small in scope), find a real artist to do graphics for you. A shiny game always draws an audience, no matter how simple the gameplay.
It is very unrealistic to think you could implement a 2D RTS engine anywhere even close to the complexity in those kind of games. You could maybe get something very rough if you were experienced, but with only one year I think it's doubtful.
I can't help but feel like it would be much better for you if you used an existing engine or framework and built off of it. Like you said, working with other code would probably be a good learning experience as well. It would allow you to experiment without getting bogged down in having to do everything.
Keep it simple or you will simply drown in complexity before getting around to have anything playable. Since you have not tried it before, you will have a lot of nuts to crack and you don't know how long they will take.
Also remember that report writing and documentation takes time too.
The idea is good, and I think you can pull off a whole game if you find good building blocks. I would suggest discussing this with your teacher to hear what is acceptable for you to use. Would it e.g. be ok to do a game on an open source engine if you add some non-trivial functionality?
Update: Seems to be several engines available from Java at http://www.devmaster.net/engines/list.php?fid=6&sid=1
People often forget, that creating games is MUCH MORE than just coding the technique thing. Its about content creation, game design, sound and music, the "fun factor". If you make heavy use of existent APIs or engines, it will be possible, but writing it from scratch with no experience in 3 month is like asking yourself if you can code 100,000 LOC in this time which means 1111 LOC per day. This might be possible, but not if you have to desing and think, and just having the code makes no game.
Perhaps it would make sense to look at some existing efforts to get a feel for the scope of what you are looking at. These should give you some ideas or even code to build on:
http://www.duncanjauncey.com/btinternet/old/javagame/game.html
http://en.wikipedia.org/wiki/Lightweight_Java_Game_Library
http://www.ardor3d.com/
http://en.wikipedia.org/wiki/JMonkeyEngine
It would be a lot for me to bite off (from scratch) in the time given that is for sure. That is about all I can say.
EDIT: I thought maybe JOGRE was not what you are looking for. Then I thought about it and it seems like it would have all the right kinds of plumbing for what you are trying to do.
EDIT AGAIN: After my answer, one of the related questions links on the side seemed relevant: Java Game Programming: JOGL vs LWJGL?
Well if it gives you any hope at all, my team and I are currently working on an RTS game called "The Genesis Project". We call ourselves MotherBoard Games, or MBG for short. If you would like, I am always looking for more coders. You can email me at mpmn5891#gmail.com, I can give you some advice and tips form my 6 year experience, 2 of which have been spent making this game (to give you a scope)

How do I actually get somewhere in GUI programming?

I am an undergraduate student. I was exposed to basic programming couple of years back in school. Till now I have an understanding of Core Java, Core Python and basic C and C++.
Every time I start off with some GUI programming so as I can start off with a project of mine, I get boggled by the sheer amount which is to be done, API to be learnt, MVC architecture and everything programmers talk about, event handling etc etc.
Studied awt and swings for a while. Tried my hands on Qt and Gtk, could not find much of documentation. Tried to make sense of pygame. I end up at the same place, knowing the core language.
Tkinter on my zenwalk Linux is broken so could never start it athough I own a book on python with Tkinter explained.
But I end up at the same place, with just the basic understanding of the language.
Want to start over, seriously now. I would like to choose python. How should I go about studying GUI programming?
I need some Internet resources and direction so that I don't end up at the same place!
Since it sounds like you want Python GUI programming, may I suggest PyGTK?
That's probably a pretty good place to start for someone who knows Python and would like to start small on some basic GUI apps. GTK can be complex at times, but with PyGTK there's plenty of open-source example apps you can study, from simple to complex.
Edit: This tutorial from LinuxJournal seems pretty helpful.
Edit 2: Here's the tutorial from PyGTK's site, and another tutorial I randomly found from Google (seems like that whole blog is pretty useful for what you want to do, actually). Finally, the snippet at the bottom of this page might be helpful, courtesy of Ubuntu's forums.
If you are leaning more to games...
I suggest you install Pygame and Python, and go through their tutorials. The pick a simple game or graphics project and program it!
For Python GUIs I like wxPython (www.wxpython.org). It is pretty easy to get started with simple controls and layouts. It is also cross platform. Plenty of tutorials out there. Just search for wxPython tutorial.
I know how you feel--I learned a whole lot of computer programming during my CS degree but very little about GUIs. I ended up teaching myself Cocoa/Objective-C for a project. Cocoa is wonderful for GUI stuff but often a royal pain with a steep learning curve. If you don't have any experience with C programming, don't bother.
First step: familiarize yourself with the MVC (Model/View/Controller) design convention, because nearly every GUI framework will reference it. Google it--there are lots of resources about it. My quick, simple definition is:
The model level defines the data or the logical model for the application. For a web app, that would be the database. For a game, it could be stored data and game logic/rules.
The view level is what the user sees and interacts with (the GUI).
The controller level is the logic that connects the two. For example, the controller knows that when you click the "start game" button in the view level, it does some stuff with the model (say, setting up the board and the players.)
Step two: Figure out what you want. Are you interested in desktop applications specifically? Games? Web apps?
If mostly what you want to do is to be able to develop something that people would actually use, another option is to learn a web development framework. The frameworks make stuff easy for you. I love Django, personally, and if you know a little Python and a little HTML and a little about MVC, you can pick it up quickly. (Just don't be confused, because what Django calls a view is actually a controller.)
If what you want to do is games or graphics/animation stuff, check out pygame. I used it for a class project--basically taught it to myself in a couple of weeks--and it worked great.
I'd say stay as far away as you can from Java Swing/awt/etc.
I've heard good things about wxPython--I almost ended up using it instead of Cocoa, because the wx stuff is available in several programming languages and it's all cross platform.
Good luck! Stay strong! I know it's really intimidating, because I've been in your shoes. You can do it with some work, practice, and motivation.
Many have recommended wxPython, and I second their enthusiasm - it is a great framework; it also includes a serious demo (with code and live applications) which will be extremely valuable for learning.
Now, BEWARE!
It is very simple to confuse the end with the means. Programming GUIs can be extremely attractive but not very productive. In my early days I spent days and days trying to get a simple plotting application (reinventing the wheel); a simple GUI for solving quadratic equations; a simple GUI for calling database queries by clicking on certain locations on a map, etc. During all this time I never actually dug into algorithms or more general and productive computer science and computer engineering topics. In retrospect, I should have. Granted, I did learn a lot and I don't totally regret it, but my advice stands: worry about your algorithm first and about your interface second. This may not apply to every field (I am an engineer for NASA). Nowadays I work with number crunching applications with no GUIs whatsoever; I don't think they need them!
Anyway, I just wanted to share my two cents with GUI programming - have fun but don't overdo it.
What do you mean by "Graphics"? Do you mean game graphics, or do you simply mean user interface code (forms, webpages, that sort of thing)? In the case of game graphics, there's a limit to how simple things can be made, but http://www.gamedev.net, for example, has tons of introductory articles on 2d and 3d engines. For something more along the application line, you might simply download Visual Studio or Eclipse and spend some time looking at the code that is autogenerated by their WYSIWYG editors.
For GUI work in general:
Less is more
GUI work (even in productive frameworks) is about as fun and productive as painting the Eiffel Tower with a toothbrush. Go for a minimal design.
Avoid State Like The Plague
Do you put state in your GUI, or in the model? If you put it in the GUI, you are going to mess yourself up with redundant and inconsistent code paths. If you put it in the model, you risk an overly complex system that gets out of sync when your GUI fails to update from the model. Both suck.
wxPython
If you want to learn wxPython, here are a few traps I noticed:
The tutorial
Use this tutorial - http://wiki.wxpython.org/AnotherTutorial
It's the best one I found.
But remember to toggle line numbers, for easy pasting.
Events
Events are a bit like exceptions, and they are used to make things interactive.
In a vanilla python program, you write something like:
def doit(i):
print 'Doing i = ',i
for i in range(10):
doit()
print 'Results = ',result
In a GUI, you do something like:
def doit(event):
print 'An event',event,'just happened!'
event.Skip()
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'The title goes here')
frame.Bind(wx.EVT_KEY_DOWN, doit)
frame.Show()
app.MainLoop()
Every time the user presses a key down, an event will be raised. Since frame is bound to the event (frame.Bind(wx.EVT_KEY_DOWN, doit)), the function doit will be called with the event as an argument.
Printing to stderr isn't too hot in a gui, but doit could also call up a dialog, or do anything you want it to.
Also, you can generate your own events using timers.
Apps, Frames, Windows, Panels, and Sizers
Everything has a parent. If an event is raised, and the child doesn't skip it (using event.Skip()), then the parent will also have to handle the event. This is analogous to exceptions raising up to higher-level functions.
A wx.App is like the Main function.
wx.Window isn't really used. Stuff inherits from it, and it has all the methods for sizing and layout, but you don't need to know that.
wx.Frame is a floating frame, like the main window in Firefox. You will have main one frame in a basic application. If you want to edit multiple files then you might have more. A wx.Frame won't usually have parents.
wx.Panel is part of a parent window. You can have several panels inside a frame. A panel can have a wx.Frame as a parent, or it might be the child of another panel.
wx.Sizers are used to automatically layout panels inside frames (or other panels).
Code:
def doit1(event):
print 'event 1 happened'
def doit2(event):
print 'event 2 happened'
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'The title goes here')
panel_1 = wx.Panel(frame,-1,style=wx.SIMPLE_BORDER)
panel_2 = wx.Panel(frame,-1,style=wx.SIMPLE_BORDER)
panel_1.Bind(wx.EVT_KEY_DOWN, doit1)
panel_2.Bind(wx.EVT_KEY_DOWN, doit2)
panel_1.SetBackgroundColour(wx.BLACK)
panel_2.SetBackgroundColour(wx.RED)
box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(panel_1,1,wx.EXPAND)
box.Add(panel_2,1,wx.EXPAND)
frame.SetSizer(box)
frame.Show()
app.MainLoop()
I've been really bad, and not used OOP practices. Just remember that even if you hate OO in most contexts, GUI programming is the place where OOP really shines.
The MCV
I don't get MCV. I don' think you need an MCV. I think a MW (model-widget) framework is fine.
For example - 2 frames that edit the same piece of text:
class Model(object):
def __init__(self):
self.value = 'Enter a value'
self.listeners = []
def Add_listener(self,listener):
self.listeners.append(listener)
def Set(self,new_value):
self.value = new_value
for listener in self.listeners:
listener.Update(self.value)
import wx
app = wx.App()
class CVFrame(wx.Frame):
def __init__(self, parent, id, title, model):
wx.Frame.__init__(self, parent, id, title, size = (100,100))
self.button = wx.Button(self, -1, 'Set model value')
self.textctrl = wx.TextCtrl(self, -1,model.value)
self.button.Bind(wx.EVT_BUTTON,self.OnSet)
self.model = model
model.Add_listener(self)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.button,0,wx.EXPAND)
sizer.Add(self.textctrl,1,wx.EXPAND)
self.SetSize((300,100))
self.SetSizer(sizer)
self.Center()
self.Show()
def OnSet(self,event):
self.model.Set(self.textctrl.GetValue())
def Update(self,value):
self.textctrl.SetValue(value)
model = Model()
frame1 = CVFrame(None, -1, 'Frame 1',model)
frame2 = CVFrame(None, -1, 'Frame 2',model)
app.MainLoop()
wxPython has a listener-subscriber framework, which is a better version of the model I just sketched out (it uses weak refs, so deleted listeners don't hang around, and so on), but that should help you get the idea.
If you have already gone through pygame, tk, Qt, and GTK, then really the only thing left that I can think of is pyglet, which I admit I have not tried, but I have read uniformly good things about it.
Still, more than anything it sounds as though you have trouble sticking with a framework long enough to really grok it. May I recommend starting with a small project, such as Pong or Breakout, and only learning as much as you need to make it? Once you have finished one thing, you will have a feel for the library, and continuing past there is a lot easier.
whatever language you choose you will have to deal with the many details involving GUI programing. this is due to the nature of the window based environment usually used for GUI.
what can help you move forward quickly in developing GUI based application is less the language and more the IDE you use. a good IDE can do some part of the less interesting stuff for you letting you focus on the big picture.
with C# in VS 2008 its all about choosing elements and methods from lists boxes. its very easy to get started and have a working project.
you can then try to customize your application to gain better understanding of whats going on behind the scenes
One of the greatest Python GUI you can study from is the source of IDLE. It always comes with Python.
For Java, you could also look into SWT.
While I have never used AWT or Swing, I have read that SWT is the easiest of the three to learn.
Here is a decent comparison between the three.

Categories

Resources