The optimal launch angle does, indeed, depend on the launching position and the ground profile.
Assume that the initial vertical position, launch speed, launch angle, ground profile is [itex]y_{0}, v, \theta, h(x)[/itex] respectively.
Then, as a function of time, the object's vertical and horizontal positions (starting at x=0) are
[tex]y(t)=y_{0}+(v\sin\theta){t}+\frac{gt^{2}}{2}, x(t)=(v\cos\theta){t}[/tex]
The object hits the ground at some time T when y(T)=h(x(T)), that is we gain the ground state equation:
[tex]h((v\cos\theta)T)=y_{0}+(v\sin\theta)T+\frac{gT^{2}}{2}[/tex]
an equation by which we in principle can solve for the collision instant T as a function of [itex]\theta[/itex], called [itex]T(\theta)[/itex]
The RANGE is therefore the horizontal coordinate considered as a function of the launch angle:
[tex]x(\theta)=v\cos\theta{T}(\theta)[/tex]
and the optimal launch angle [itex]\theta_{op}[/itex] is determined by solving the the algebraic equation [tex]\frac{dx}{d\theta}=0[/tex], that is finding the solutions of:
[tex]-(\sin\theta_{op})T(\theta_{op})+(\cos\theta_{op})\frac{dT}{d\theta}\mid_{(\theta=\theta_{op})}=0\to\frac{1}{T(\theta_{op})}\frac{dT}{d\theta}\mid_{(\theta=\theta_{op})}=\tan(\theta_{op})[/tex]
In the general case, it is by no means a trivial matter to determine the function [itex]T(\theta)[/itex], nor is it trivial to solve the range equation for [itex]\theta_{op}[/itex]