]> git.sesse.net Git - movit/blob - effect_chain.h
Use abort() on check_error() failure.
[movit] / effect_chain.h
1 #ifndef _MOVIT_EFFECT_CHAIN_H
2 #define _MOVIT_EFFECT_CHAIN_H 1
3
4 // An EffectChain is the largest basic entity in Movit; it contains everything
5 // needed to connects a series of effects, from inputs to outputs, and render
6 // them. Generally you set up your effect chain once and then call its render
7 // functions once per frame; setting one up can be relatively expensive,
8 // but rendering is fast.
9 //
10 // Threading considerations: EffectChain is “thread-compatible”; you can use
11 // different EffectChains in multiple threads at the same time (assuming the
12 // threads do not use the same OpenGL context, but this is a good idea anyway),
13 // but you may not use one EffectChain from multiple threads simultaneously.
14 // You _are_ allowed to use one EffectChain from multiple threads as long as
15 // you only use it from one at a time (possibly by doing your own locking),
16 // but if so, the threads' contexts need to be set up to share resources, since
17 // the EffectChain holds textures and other OpenGL objects that are tied to the
18 // context.
19
20 #include <GL/glew.h>
21 #include <stdio.h>
22 #include <map>
23 #include <set>
24 #include <string>
25 #include <vector>
26
27 #include "image_format.h"
28
29 namespace movit {
30
31 class Effect;
32 class Input;
33 struct Phase;
34 class ResourcePool;
35
36 // For internal use within Node.
37 enum AlphaType {
38         ALPHA_INVALID = -1,
39         ALPHA_BLANK,
40         ALPHA_PREMULTIPLIED,
41         ALPHA_POSTMULTIPLIED,
42 };
43
44 // Whether you want pre- or postmultiplied alpha in the output
45 // (see effect.h for a discussion of pre- versus postmultiplied alpha).
46 enum OutputAlphaFormat {
47         OUTPUT_ALPHA_FORMAT_PREMULTIPLIED,
48         OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED,
49 };
50
51 // A node in the graph; basically an effect and some associated information.
52 class Node {
53 public:
54         Effect *effect;
55         bool disabled;
56
57         // Edges in the graph (forward and backward).
58         std::vector<Node *> outgoing_links;
59         std::vector<Node *> incoming_links;
60
61 private:
62         // Logical size of the output of this effect, ie. the resolution
63         // you would get if you sampled it as a texture. If it is undefined
64         // (since the inputs differ in resolution), it will be 0x0.
65         // If both this and output_texture_{width,height} are set,
66         // they will be equal.
67         unsigned output_width, output_height;
68
69         // If output goes to RTT, which phase it is in (otherwise unset).
70         // This is a bit ugly; we should probably fix so that Phase takes other
71         // phases as inputs, instead of Node.
72         Phase *phase;
73
74         // Used during the building of the effect chain.
75         Colorspace output_color_space;
76         GammaCurve output_gamma_curve;
77         AlphaType output_alpha_type;
78
79         friend class EffectChain;
80 };
81
82 // A rendering phase; a single GLSL program rendering a single quad.
83 struct Phase {
84         GLuint glsl_program_num;  // Owned by the resource_pool.
85         bool input_needs_mipmaps;
86
87         // Inputs are only inputs from other phases (ie., those that come from RTT);
88         // input textures are not counted here.
89         std::vector<Node *> inputs;
90
91         std::vector<Node *> effects;  // In order.
92         unsigned output_width, output_height, virtual_output_width, virtual_output_height;
93
94         // Identifier used to create unique variables in GLSL.
95         // Unique per-phase to increase cacheability of compiled shaders.
96         std::map<Node *, std::string> effect_ids;
97 };
98
99 class EffectChain {
100 public:
101         // Aspect: e.g. 16.0f, 9.0f for 16:9.
102         // resource_pool is a pointer to a ResourcePool with which to share shaders
103         // and other resources (see resource_pool.h). If NULL (the default),
104         // will create its own that is not shared with anything else. Does not take
105         // ownership of the passed-in ResourcePool, but will naturally take ownership
106         // of its own internal one if created.
107         EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool = NULL);
108         ~EffectChain();
109
110         // User API:
111         // input, effects, output, finalize need to come in that specific order.
112
113         // EffectChain takes ownership of the given input.
114         // input is returned back for convenience.
115         Input *add_input(Input *input);
116
117         // EffectChain takes ownership of the given effect.
118         // effect is returned back for convenience.
119         Effect *add_effect(Effect *effect) {
120                 return add_effect(effect, last_added_effect());
121         }
122         Effect *add_effect(Effect *effect, Effect *input) {
123                 std::vector<Effect *> inputs;
124                 inputs.push_back(input);
125                 return add_effect(effect, inputs);
126         }
127         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2) {
128                 std::vector<Effect *> inputs;
129                 inputs.push_back(input1);
130                 inputs.push_back(input2);
131                 return add_effect(effect, inputs);
132         }
133         Effect *add_effect(Effect *effect, const std::vector<Effect *> &inputs);
134
135         void add_output(const ImageFormat &format, OutputAlphaFormat alpha_format);
136
137         // Set number of output bits, to scale the dither.
138         // 8 is the right value for most outputs.
139         // The default, 0, is a special value that means no dither.
140         void set_dither_bits(unsigned num_bits)
141         {
142                 this->num_dither_bits = num_bits;
143         }
144
145         void finalize();
146
147
148         //void render(unsigned char *src, unsigned char *dst);
149         void render_to_screen()
150         {
151                 render_to_fbo(0, 0, 0);
152         }
153
154         // Render the effect chain to the given FBO. If width=height=0, keeps
155         // the current viewport.
156         void render_to_fbo(GLuint fbo, unsigned width, unsigned height);
157
158         Effect *last_added_effect() {
159                 if (nodes.empty()) {
160                         return NULL;
161                 } else {
162                         return nodes.back()->effect;
163                 }       
164         }
165
166         // API for manipulating the graph directly. Intended to be used from
167         // effects and by EffectChain itself.
168         //
169         // Note that for nodes with multiple inputs, the order of calls to
170         // connect_nodes() will matter.
171         Node *add_node(Effect *effect);
172         void connect_nodes(Node *sender, Node *receiver);
173         void replace_receiver(Node *old_receiver, Node *new_receiver);
174         void replace_sender(Node *new_sender, Node *receiver);
175         void insert_node_between(Node *sender, Node *middle, Node *receiver);
176
177         // Get the current resource pool assigned to this EffectChain.
178         // Primarily to let effects allocate textures as needed.
179         // Any resources you get from the pool must be returned to the pool
180         // no later than in the Effect's destructor.
181         ResourcePool *get_resource_pool() { return resource_pool; }
182
183 private:
184         // Make sure the output rectangle is at least large enough to hold
185         // the given input rectangle in both dimensions, and is of the
186         // current aspect ratio (aspect_nom/aspect_denom).
187         void size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height);
188
189         // Compute the input sizes for all inputs for all effects in a given phase,
190         // and inform the effects about the results.    
191         void inform_input_sizes(Phase *phase);
192
193         // Determine the preferred output size of a given phase.
194         // Requires that all input phases (if any) already have output sizes set.
195         void find_output_size(Phase *phase);
196
197         // Find all inputs eventually feeding into this effect that have
198         // output gamma different from GAMMA_LINEAR.
199         void find_all_nonlinear_inputs(Node *effect, std::vector<Node *> *nonlinear_inputs);
200
201         // Create a GLSL program computing the given effects in order.
202         Phase *compile_glsl_program(const std::vector<Node *> &inputs,
203                                     const std::vector<Node *> &effects);
204
205         // Create all GLSL programs needed to compute the given effect, and all outputs
206         // that depends on it (whenever possible).
207         void construct_glsl_programs(Node *output);
208
209         // Output the current graph to the given file in a Graphviz-compatible format;
210         // only useful for debugging.
211         void output_dot(const char *filename);
212         std::vector<std::string> get_labels_for_edge(const Node *from, const Node *to);
213         void output_dot_edge(FILE *fp,
214                              const std::string &from_node_id,
215                              const std::string &to_node_id,
216                              const std::vector<std::string> &labels);
217
218         // Some of the graph algorithms assume that the nodes array is sorted
219         // topologically (inputs are always before outputs), but some operations
220         // (like graph rewriting) can change that. This function restores that order.
221         void sort_all_nodes_topologically();
222
223         // Do the actual topological sort. <nodes> must be a connected, acyclic subgraph;
224         // links that go to nodes not in the set will be ignored.
225         std::vector<Node *> topological_sort(const std::vector<Node *> &nodes);
226
227         // Utility function used by topological_sort() to do a depth-first search.
228         // The reason why we store nodes left to visit instead of a more conventional
229         // list of nodes to visit is that we want to be able to limit ourselves to
230         // a subgraph instead of all nodes. The set thus serves a dual purpose.
231         void topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list);
232
233         // Used during finalize().
234         void find_color_spaces_for_inputs();
235         void propagate_alpha();
236         void propagate_gamma_and_color_space();
237         Node *find_output_node();
238
239         bool node_needs_colorspace_fix(Node *node);
240         void fix_internal_color_spaces();
241         void fix_output_color_space();
242
243         bool node_needs_alpha_fix(Node *node);
244         void fix_internal_alpha(unsigned step);
245         void fix_output_alpha();
246
247         bool node_needs_gamma_fix(Node *node);
248         void fix_internal_gamma_by_asking_inputs(unsigned step);
249         void fix_internal_gamma_by_inserting_nodes(unsigned step);
250         void fix_output_gamma();
251         void add_dither_if_needed();
252
253         float aspect_nom, aspect_denom;
254         ImageFormat output_format;
255         OutputAlphaFormat output_alpha_format;
256
257         std::vector<Node *> nodes;
258         std::map<Effect *, Node *> node_map;
259         Effect *dither_effect;
260
261         std::vector<Input *> inputs;  // Also contained in nodes.
262         std::vector<Phase *> phases;
263
264         unsigned num_dither_bits;
265         bool finalized;
266
267         ResourcePool *resource_pool;
268         bool owns_resource_pool;
269 };
270
271 }  // namespace movit
272
273 #endif // !defined(_MOVIT_EFFECT_CHAIN_H)