EXCLUSIVE

Jason Patric just won a 2-year legal battle against his baby mama -- with a judge just declaring he is the legal father of 4-year-old Gus ... TMZ has learned.

Jason had a baby with ex-GF Danielle Schreiber, and after breaking up -- getting back together and breaking up again -- she fought hard against his bid to become the legal father, citing a quirky law.

According to the law ... if a man donates sperm to a woman to whom he is not married and a doctor facilitates the insemination ... the man has NO claim of custody or parental rights.

The trial judge ruled against Jason, he appealed and the appellate court said the trial judge was off base and sent it back for another hearing.

The second time was a charm for Jason. We've learned the trial judge just issued a sealed 45-page opinion ... concluding Jason is the legal father.

The judge ordered Jason, Danielle and their lawyers to try and hash out a custody, visitation and support agreement ... but if they can't, the judge will make the decisions.

This case became a rallying cry for father's rights -- and an enormous victory for Jason.